Scala 2 到 Scala 3:实例化特征不再识别新方法

问题描述 投票:0回答:1

以下代码在 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 traits anonymous-class scala-3
1个回答
0
投票

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)
}
© www.soinside.com 2019 - 2024. All rights reserved.