加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为什么这个case类可以包含比声明更多的参数?

发布时间:2020-12-16 19:18:53 所属栏目:安全 来源:网络整理
导读:看代码, 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,4-). 令我惊讶的是,
看代码,

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,4-).

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

解决方法

它被称为自动元组.

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

Wrapped(1,4)

自动变成了

Wrapped((1,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)
                 ^
<console>:10: error: too many arguments for method apply: (a: (Int,Int))Foo[(Int,Int)] in object Foo
              Foo(1,2)
                 ^

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读