Scala - 特征 returns 不同的对象
Scala - Trait returns different objects
我对 Scala 中的特征有疑问。
我有一个特征 returns 一种对象类型(AA 或 BB)取决于参数国家/地区的值。
我的实现包括以下方法:
trait firstT{
def GetType(country: String) : OType = {
//i would like to call OType.load(country)
}
}
trait OType[T <: OType[T]] {
def load(country: String): OType[T] = ???
//I would like to return AA or BB depending on country
}
class AA extends OType[AA] {
override def load(country: String): AA = new AA
}
class BB extends OType[BB] {
override def load(country: String): BB = new BB
}
你能帮我解决这个问题吗?
谢谢
最好的问候
load
是特征的“静态”方法,因此它属于伴随对象而不是 class 定义。
所以您想要的代码可能如下所示
trait firstT {
def GetType(country: String): OType = {
OType.load(country)
}
}
trait OType
object OType {
def load(country: String): OType =
if (country == "AA") {
AA.load()
} else {
BB.load()
}
}
class AA extends OType
object AA {
def load(): AA = new AA
}
class BB extends OType
object BB {
def load(): BB = new BB
}
如果你真的需要 OType
特征按类型参数化然后使用 abstract type member:
trait OType {
type T <: OType
}
class AA extends OType {
type T = AA
}
class BB extends OType {
type T = BB
}
我对 Scala 中的特征有疑问。
我有一个特征 returns 一种对象类型(AA 或 BB)取决于参数国家/地区的值。
我的实现包括以下方法:
trait firstT{
def GetType(country: String) : OType = {
//i would like to call OType.load(country)
}
}
trait OType[T <: OType[T]] {
def load(country: String): OType[T] = ???
//I would like to return AA or BB depending on country
}
class AA extends OType[AA] {
override def load(country: String): AA = new AA
}
class BB extends OType[BB] {
override def load(country: String): BB = new BB
}
你能帮我解决这个问题吗? 谢谢 最好的问候
load
是特征的“静态”方法,因此它属于伴随对象而不是 class 定义。
所以您想要的代码可能如下所示
trait firstT {
def GetType(country: String): OType = {
OType.load(country)
}
}
trait OType
object OType {
def load(country: String): OType =
if (country == "AA") {
AA.load()
} else {
BB.load()
}
}
class AA extends OType
object AA {
def load(): AA = new AA
}
class BB extends OType
object BB {
def load(): BB = new BB
}
如果你真的需要 OType
特征按类型参数化然后使用 abstract type member:
trait OType {
type T <: OType
}
class AA extends OType {
type T = AA
}
class BB extends OType {
type T = BB
}