在实现 Scala 特征或抽象类的案例类中使用默认值

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

有没有办法获取此代码的版本以使用特征中定义的默认值?

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
scala abstract-class traits
1个回答
0
投票

基于您除了该代码之外没有提供任何其他内容,我只能建议如何使其编译,但我认为设计并不是很好。

对于第一种方法

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)

}

如果方法

x
y
没有关系,您可以在不同的特征/类/单例中使用

© www.soinside.com 2019 - 2024. All rights reserved.