以下代码在 Scala 2 中编译并运行:
trait SomeTrait {
val myName: String
}
class SomeClass() extends SomeTrait {
override val myName: String = "Billy Banana"
}
val someClass = new SomeClass()
println(someClass.myName)
val extendedTrait = new SomeTrait {
override val myName: String = "Amy Apples"
def printName(): Unit = println(myName)
}
extendedTrait.printName()
但是在 Scala 3 中,这一行出现编译错误:
extendedTrait.printName()
Scala 3 文档中的哪些内容引用了此更改?
Scala 2 默认情况下会推断结构类型,Scala 3 则不会。
val foo = new {
def bar: Unit = ???
}
// Scala 2:
// foo: AnyRef { def bar: Unit }
// Scala 3:
// foo: AnyRef
您必须明确地将其设为结构类型:
val extendedTrait: SomeTrait {
def printName(): Unit
} = new SomeTrait {
override val myName: String = "Amy Apples"
def printName(): Unit = println(myName)
}