gpt4 book ai didi

scala - 具有类型参数的案例类的元组方法

转载 作者:行者123 更新时间:2023-12-04 10:07:18 25 4
gpt4 key购买 nike

当有一个带有类型参数的案例类时,我看不到如何调用 tupled方法。似乎可以通过 apply 找到和 unapply .

scala> case class Foo[T](x:T, y:T)
defined class Foo

scala> Foo.apply[Int] _
res1: (Int, Int) => Foo[Int] = <function2>

scala> Foo.unapply[Int] _
res2: Foo[Int] => Option[(Int, Int)] = <function1>

scala> Foo.tupled[Int] _
<console>:10: error: value tupled is not a member of object Foo
Foo.tupled[Int] _
^

知道发生了什么吗?

最佳答案

tl;博士

案例类的伴随对象不能扩展 FunctionN (定义 tupled ,带有 N >= 2)当它们具有类型参数时。采用

(Foo[Int] _).tupled

讨论

当您有 Vanilla 类(class)时,例如
case class Bar(x: Int, y: Int)

它的构造函数实际上是 Function2[Int, Int, Bar] ,因此当编译器生成伴随对象 Bar它可以方便地使其扩展 Function2 .

然后生成的代码将是
class Bar extends AnyRef with Product with Serializable { ... }
object Bar extends Function2[Int, Int, Bar] with Serializable { ... }

现在考虑
case class Foo[T](x: T, y: T)

如果您尝试使用相同的技巧,您很快就会发现自己陷入困境:
// this can't compile, what's T?
object Foo extends Function2[T, T, Bar] with Serializable { ... }

由于 T未知,编译器无法生成 Foo Function2 的子类它不能做得比让它扩展 AnyRef 更好。 :
class Foo[T] extends AnyRef with Product with Serializable { ... }
object Foo extends AnyRef with Serializable { ... }

这是上面讨论的快速证明(使用 scala -Xprint:typer ):
scala> case class Bar(x: Int, y: Int)
...
<synthetic> object Bar extends scala.runtime.AbstractFunction2[Int,Int,Bar] with Serializable {
...

scala> case class Foo[T](x: T, y: T)
...
<synthetic> object Foo extends AnyRef with Serializable {
...

总结一下,当你有类型参数时,你必须获得一个 Function2第一的
val f: Function2[Int, Int, Foo] = Foo[Int] _

然后您可以调用 tupled在上面
f.tupled // ((Int, Int)) => Foo[Int]

关于scala - 具有类型参数的案例类的元组方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25345211/

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