2
這裏是我的問題:斯卡拉implicits和覆蓋問題
trait Caller {
type EntityType
def parseEntity(entity: String): EntityType
}
trait IntCaller extends Caller {
implicit def strToInt(s: String) = s.toInt
override type EntityType = Int
override def parseEntity(entity: String): EntityType = entity
}
trait DoubleCaller extends Caller {
implicit def strToDouble(s: String) = s.toDouble
override type EntityType = Double
override def parseEntity(entity: String): EntityType = entity
}
object main {
def main(args: Array[String]): Unit = {
val intCaller = new IntCaller{}
val doubleCaller = new DoubleCaller{}
println("Result is: " + intCaller.parseEntity("5"))
println("Result is: " + doubleCaller.parseEntity("5.0"))
}
}
正如你可以看到我不斷重複的代碼爲:parseEntity
方法。如果我想添加一個FloatCaller
,我將不得不重寫parseEntity
,即使它的實現是相同的。
如何在Caller
中寫入parseEntity的實現,以便我不必一次又一次地在子特徵中編寫相同的代碼?
免責聲明: 這是一個真正的問題簡化我與SprayJsonSupport
從akka.http.scaladsl.marshallers.sprayjson
。