在实现它的case类中为Scala trait或抽象类使用默认值

xwbd5t1u  于 12个月前  发布在  Scala
关注(0)|答案(1)|浏览(156)

有没有办法让这段代码的版本使用trait中定义的默认值?

trait A {      // alternately `abstract class A`
 def x: String
 def y: Int = 1
}

final case class B(x: String, y: Int) extends A

val b = B("ok") // -> errors out
// I'd like this to turn into a B("ok", 1), 
// by using the default y value from A, but this doesn't work
// and similarly something like
object B {
 def apply(x: String): B = {B(x, A.y)}
} 
// doesn't work either

字符串

col17t5w

col17t5w1#

基于你没有提供任何东西比代码,我只能建议如何使它编译,但我不认为设计是完全好的。
对于第一种方法

trait A {
  def x: String
  def y: Int = 1
}

object DefaultA extends A {
  def x = ??? // you need something here, which means a default impl for this singleton
}

final case class B(x: String, override val y: Int = DefaultA.y) extends A

val b = B("ok") // this will compile

字符串
对于第二种情况

trait A {
  def x: String
  def y: Int = 1
}

final case class B(x: String, override val y: Int) extends A

object B {
  def apply(x: String): B =
    // here you create an anonymous instance of the trait but again 
    // you have to provide an implementation for the other method
    B(x, (new A { override def x: String = ??? }).y)

}


如果方法xy没有关系,你可以在不同的traits/classes/singletons中使用

相关问题