如何调用 Scala 抽象类型的构造函数? [英] How can I invoke the constructor of a Scala abstract type?
问题描述
我正在尝试弄清楚如何为 Scala 抽象类型调用构造函数:
I'm trying to figure out how to invoke a constructor for a Scala abstract type:
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 清单 但我不清楚他们如何在这里提供帮助.同样,我无法弄清楚如何对伴随对象的 apply() 构造函数执行相同的操作:
Is this even feasible? I'm familiar with Scala manifests but I'm not clear how they could help here. Likewise I can't figure out how to do the same with a companion object's apply() constructor:
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
}
}
感谢收到任何想法!
推荐答案
没有直接的方法来调用构造函数或访问仅给定类型的伴随对象.一种解决方案是使用类型类来构造给定类型的默认实例.
There is no direct way to invoke the constructor or access the companion object given only a type. One solution would be to use a type class that constructs a default instance of the given type.
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
定义.
You will need to add an implicit Default
definition to all companion objects of classes that support creation of a default instance.
这篇关于如何调用 Scala 抽象类型的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!