gpt4 book ai didi

scala - 为什么这个案例类可以容纳比它声明的更多的参数?

转载 作者:行者123 更新时间:2023-12-01 22:59:08 24 4
gpt4 key购买 nike

查看代码,

 case class Wrapped[A](elem: A)(implicit ordering: Ordering[A])
extends Ordered[Wrapped[A]] {
def compare(that: Wrapped[A]): Int = ordering.compare(this.elem, that.elem)
}

我在这里定义了一个案例类

然后调用

包裹(1,2,2,4)

令我惊讶的是,即使是 Wrapped(1,2,3,4,5) (任意数量的参数)也可以正常工作而不会出现编译错误。

最佳答案

这称为自动tupling。

编译器将尝试通过将所有额外参数包装在一个元组中来弥补额外的参数。

Wrapped(1,2,3,4)

自动变成

Wrapped((1,2,3,4))

顺便说一句,这是一个令人烦恼且令人惊讶的功能,我真的希望它最终会被弃用。同时,您有两个可用的编译器选项:

  • -Ywarn-adapted-args,在自动匹配时发出警告
  • -Yno-adapted-args,在相同情况下给出错误

带有警告的示例:

scala -Ywarn-adapted-args

scala> case class Foo[A](a: A)

scala> Foo(1, 2)
<console>:10: warning: Adapting argument list by creating a 2-tuple: this may not be what you want.
signature: Foo.apply[A](a: A): Foo[A]
given arguments: 1, 2
after adaptation: Foo((1, 2): (Int, Int))
Foo(1, 2)
^
res1: Foo[(Int, Int)] = Foo((1,2))

错误示例:

scala -Yno-adapted-args

scala> case class Foo[A](a: A)
defined class Foo

scala> Foo(1, 2)
<console>:10: warning: No automatic adaptation here: use explicit parentheses.
signature: Foo.apply[A](a: A): Foo[A]
given arguments: 1, 2
after adaptation: Foo((1, 2): (Int, Int))
Foo(1, 2)
^
<console>:10: error: too many arguments for method apply: (a: (Int, Int))Foo[(Int, Int)] in object Foo
Foo(1, 2)
^

关于scala - 为什么这个案例类可以容纳比它声明的更多的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29252205/

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