默认类型参数化函数文字类参数
这是一个预期的行为还是一个错误?考虑以下特征(无论是一个类,都没关系):
trait P[T] {
class Inner(val f: T => Unit = _ => println("nope"))
}
这是我所期望的:
scala> val p = new P[Int] {
| val inner = new Inner
| }
p: java.lang.Object with P[Int]{def inner: this.Inner} = $anon$1@12192a9
scala> p.inner.f(5)
nope
但是这个?
scala> val p = new P[Int] {
| val inner = new Inner() {
| println("some primary constructor code in here")
| }
| }
<console>:6: error: type mismatch;
found : (T) => Unit
required: (Int) => Unit
val inner = new Inner() {
^
Is this an intended behavior or is it a bug? Consider the following trait (be it a class, doesn't matter):
trait P[T] {
class Inner(val f: T => Unit = _ => println("nope"))
}
This is what I would have expected:
scala> val p = new P[Int] {
| val inner = new Inner
| }
p: java.lang.Object with P[Int]{def inner: this.Inner} = $anon$1@12192a9
scala> p.inner.f(5)
nope
But this?
scala> val p = new P[Int] {
| val inner = new Inner() {
| println("some primary constructor code in here")
| }
| }
<console>:6: error: type mismatch;
found : (T) => Unit
required: (Int) => Unit
val inner = new Inner() {
^
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这似乎是一个错误,尽管是在嵌套类、抽象类型和默认参数之间相当模糊的交集处。您可以在 Scala 错误跟踪器 中提出问题单 - 我找不到现有的问题单描述这一点。
这是打字阶段之后的样子:
以及工作版本,没有扩展 Inner 的匿名内部类。
That appears to be a bug, albeit at a rather obscure intersection between nested classes, abstract types, and default parameters. You could raise a ticket in the Scala bug tracker -- I couldn't find an existing ticket describing this.
Here's how it looks after the typer phase:
And the working version, without the anonymous inner class extending Inner.