Scala:return 一个参数化实例
Scala: return a parametrized instance
我无法使用以下代码:
object Factory {
def apply[U <: Cda](type: MyType.Value): MyUtilTrait[U] = {
type match {
case MyType.Value.one => MyOneUtilCustom
case MyType.Value.two => MyTwoUtilCustom
}
}
}
=> Factory.MyType 类型的表达式不符合预期类型 MyUtilTrait[U]
trait MyUtilTrait[T <: Cda] {}
object MyOneUtilCustom extends MyUtilTrait[CdaOneCustom] { }
object MyTwoUtilCustom extends MyUtilTrait[CdaTwoCustom] { }
case class CdaOneCustom(...) extends Cda {}
case class CdaTwoCustom(...) extends Cda {}
abstract class Cda(...) {}
object MyType extends Enumeration {
val one, two = Value
}
通过应用,我应该return 一个用 Cda 子类型参数化的 MyUtilTrait,所以有什么问题吗?
用这样的签名 [1] 实现这个 apply
方法几乎是完全不可能的,因为有人可以来定义
class Unobtanium extends Cda {
// implement all `Cda` methods by `???`
}
然后调用
Factory.apply[Unobtanium](MyType.one)
一个工厂如果对Unobtanium
一无所知,又是第一次见到这种奇怪的类型,怎么会创建一个MyUtilTrait[Unobtanium]
?
改用存在类型:
abstract class Cda {}
case class CdaOneCustom() extends Cda {}
case class CdaTwoCustom() extends Cda {}
trait MyUtilTrait[T <: Cda] {}
object MyOneUtilCustom extends MyUtilTrait[CdaOneCustom] { }
object MyTwoUtilCustom extends MyUtilTrait[CdaTwoCustom] { }
object MyType extends Enumeration {
val one, two = Value
}
object Factory {
def apply(typ: MyType.Value): MyUtilTrait[_] = {
import MyType._
typ match {
case `one` => MyOneUtilCustom
case `two` => MyTwoUtilCustom
}
}
}
[1] 除非你的 MyUtilTrait[X]
是微不足道的东西,比如 Nil
(对于任何 X
), 或某种 Consumer[Any]
,它实际上并不关心类型参数。
我无法使用以下代码:
object Factory {
def apply[U <: Cda](type: MyType.Value): MyUtilTrait[U] = {
type match {
case MyType.Value.one => MyOneUtilCustom
case MyType.Value.two => MyTwoUtilCustom
}
}
}
=> Factory.MyType 类型的表达式不符合预期类型 MyUtilTrait[U]
trait MyUtilTrait[T <: Cda] {}
object MyOneUtilCustom extends MyUtilTrait[CdaOneCustom] { }
object MyTwoUtilCustom extends MyUtilTrait[CdaTwoCustom] { }
case class CdaOneCustom(...) extends Cda {}
case class CdaTwoCustom(...) extends Cda {}
abstract class Cda(...) {}
object MyType extends Enumeration {
val one, two = Value
}
通过应用,我应该return 一个用 Cda 子类型参数化的 MyUtilTrait,所以有什么问题吗?
用这样的签名 [1] 实现这个 apply
方法几乎是完全不可能的,因为有人可以来定义
class Unobtanium extends Cda {
// implement all `Cda` methods by `???`
}
然后调用
Factory.apply[Unobtanium](MyType.one)
一个工厂如果对Unobtanium
一无所知,又是第一次见到这种奇怪的类型,怎么会创建一个MyUtilTrait[Unobtanium]
?
改用存在类型:
abstract class Cda {}
case class CdaOneCustom() extends Cda {}
case class CdaTwoCustom() extends Cda {}
trait MyUtilTrait[T <: Cda] {}
object MyOneUtilCustom extends MyUtilTrait[CdaOneCustom] { }
object MyTwoUtilCustom extends MyUtilTrait[CdaTwoCustom] { }
object MyType extends Enumeration {
val one, two = Value
}
object Factory {
def apply(typ: MyType.Value): MyUtilTrait[_] = {
import MyType._
typ match {
case `one` => MyOneUtilCustom
case `two` => MyTwoUtilCustom
}
}
}
[1] 除非你的 MyUtilTrait[X]
是微不足道的东西,比如 Nil
(对于任何 X
), 或某种 Consumer[Any]
,它实际上并不关心类型参数。