我试图弄清楚如何调用 Scala 抽象类型的构造函数:
class Journey(val length: Int)
class PlaneJourney(length: Int) extends Journey(length)
class BoatJourney(length: Int) extends Journey(length)
class Port[J <: Journey] {
def startJourney: J = {
new J(23) // error: class type required but J found
}
}
这可行吗?我熟悉Scala 体现 https://stackoverflow.com/questions/3213510/what-is-a-manifest-in-scala-and-when-do-you-need-it但我不清楚他们如何在这里提供帮助。同样,我不知道如何对伴生对象的 apply() 构造函数执行相同的操作:
object Journey { def apply() = new Journey(0) }
object PlaneJourney { def apply() = new PlaneJourney(0) }
object BoatJourney { def apply() = new BoatJourney(0) }
class Port[J <: Journey] {
def startJourney: J = {
J() // error: not found: value J
}
}
任何想法都感激不尽!
没有直接的方法来调用构造函数或访问仅给定类型的伴生对象。一种解决方案是使用构造给定类型的默认实例的类型类。
trait Default[A] { def default: A }
class Journey(val length: Int)
object Journey {
// Provide the implicit in the companion
implicit def default: Default[Journey] = new Default[Journey] {
def default = new Journey(0)
}
}
class Port[J <: Journey : Default] {
// use the Default[J] instance to create the instance
def startJourney: J = implicitly[Default[J]].default
}
您将需要添加一个隐式Default
定义支持创建默认实例的类的所有伴生对象。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)