gpt4 book ai didi

scala - 如何绕过 Scala 案例类 22 个字段的限制?

转载 作者:行者123 更新时间:2023-12-03 06:12:17 25 4
gpt4 key购买 nike

Scala 案例类的构造函数中的字段数限制为 22 个。我想超越这个限制,有没有办法通过适用于案例类的继承或组合来实现这一点?

最佳答案

最近(2016 年 10 月,OP 发布六年后),来自 Scala and 22 的博客文章“Richard Dallaway”探索这个限制:

Back in 2014, when Scala 2.11 was released, an important limitation was removed:

Case classes with > 22 parameters are now allowed. 

也就是说,案例类字段的数量仍然存在限制,请参阅https://stackoverflow.com/a/55498135/1586965

This may lead you to think there are no 22 limits in Scala, but that’s not the case. The limit lives on in functions and tuples.

The fix (PR 2305) introduced in Scala 2.11 removed the limitation for the above common scenarios: constructing case classes, field access (including copying), and pattern matching (baring edge cases).

It did this by omitting unapply and tupled for case classes above 22 fields.
In other words, the limit to Function22 and Tuple22 still exists.

Working around the Limit (post Scala 2.11)

There are two common tricks for getting around this limit.

  • The first is to use nested tuples.
    Although it’s true a tuple can’t contain more than 22 elements, each element itself could be a tuple

  • The other common trick is to use heterogeneous lists (HLists), where there’s no 22 limit.

If you want to make use of case classes, you may be better off using the shapeless HList implementation. We’ve created the Slickless library to make that easier. In particular the recent mappedWith method converts between shapeless HLists and case classes. It looks like this:

import slick.driver.H2Driver.api._
import shapeless._
import slickless._

class LargeTable(tag: Tag) extends Table[Large](tag, "large") {
def a = column[Int]("a")
def b = column[Int]("b")
def c = column[Int]("c")
/* etc */
def u = column[Int]("u")
def v = column[Int]("v")
def w = column[Int]("w")

def * = (a :: b :: c :: /* etc */ :: u :: v :: w :: HNil)
.mappedWith(Generic[Large])
}

There’s a full example with 26 columns in the Slickless code base.

关于scala - 如何绕过 Scala 案例类 22 个字段的限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20258417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com