我在 scala 2.12 上有点挣扎:
我有以下层次结构:
trait A
case class B(format: String) extends A
trait Writer {
def write(config: A): Unit
}
val writer = new Writer {
override def write(config: A) = println("hi")
}
val w = B("console")
writer.write(w)
效果很好。但我想为 writer 提供一个替代实现:
val writer = new Writer {
override def write(config: B) = println("hi")
}
但我明白了object creation impossible, since method write in trait Writer of type (config: Playground.A)Unit is not defined
我假设由于 B 是 A,这应该有效。如何使用wherewrite
类型的配置覆盖B
B <: A
斯卡斯蒂:https ://scastie.scala-lang.org/QBaiiDP4Sj2lptUjrWLJYw
编辑: - - - - - - - - - - - - - - - - - - - - - - - - ------------
根据一些输入,我将实现更改为:
sealed trait A
case class B(format: String) extends A
trait Writer[+T] {
def write[S >: T](config: S): Unit
}
val writer: Writer[A] = new Writer[B] {
override def write[B](config: B) = println("hi")
}
val b = B("console")
writer.write(b)
哪个有效。
但是,如果我修改它以访问 中的变量config
,它会中断:
sealed trait A
case class B(format: String) extends A
trait Writer[+T] {
def write[S >: T](config: S): Unit
}
val writer: Writer[A] = new Writer[B] {
override def write[B](config: B) = println(config.format)
}
val b = B("console")
writer.write(b)
和value format is not a member of type parameter B
https://scastie.scala-lang.org/Xj2rKbbiTmG7raZgQZYfHA
欣赏输入。