[英]Scala implicits and overrides problems
这是我的问题:
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
。
我怎么能写在了parseEntity的implentation Caller
,让我不必一次又一次地写在孩子的性状相同的代码?
免责声明:这是对SprayJsonSupport
的akka.http.scaladsl.marshallers.sprayjson
的实际问题的简化。
给定转换函数,使用可以构建Caller
实例的工厂方法会更好。 这之间的唯一不同IntCaller
和DoubleCaller
是toInt
和toDouble
(和类型,当然)。
trait Caller {
type EntityType
def parseEntity(entity: String): EntityType
}
object Caller {
def apply[A](f: String => A): Caller = new Caller {
type EntityType = A
def parseEntity(entity: String): EntityType = f(entity)
}
}
scala> val IntCaller = Caller(_.toInt)
scala> IntCaller.parseEntity("123")
res1: IntCaller.EntityType = 123
scala> val DoubleCaller = Caller(_.toDouble)
scala> DoubleCaller.parseEntity("1.23")
res2: DoubleCaller.EntityType = 1.23
如果要继续使用继承,请继续强制子类或特征使用parseEntity
实现转换。 不过,使用隐式转换并不是真正必要的。 出现重复代码的唯一原因是因为隐式转换使parseEntity
对于每个实现看起来都一样,即使实际上不是(因为它需要解析不同的隐式)。
trait Caller {
type EntityType
def parseEntity(entity: String): EntityType
}
trait IntCaller {
type EntityType = Int
def parseEntity(entity: String): EntityType = entity.toInt
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.