为什么Scala编译器无法编译下一个代码:
trait Profile {}
class SomeProfile extends Profile
trait Foo {
def get[T <: Profile]: Option[T]
}
object Example {
val foo: Foo = new Foo {
// This works (but might give runtime exception), but it is not ugly? :)
def get[T <: Profile]: Option[T] = Some((new SomeProfile).asInstanceOf[T])
}
val foo2: Foo = new Foo {
// This does not compile with type mismatch :(
def get[T <: Profile]: Option[T] = Some(new SomeProfile)
}
}
编译器说:
type mismatch;
found : Playground.this.SomeProfile
required: T
但SomeProfile
是T
,不是吗?
我想用确切的类型实现此特征DatabaseConfigProvider并以这种方式做到这一点:
val dc: DatabaseConfig[JdbcProfile] = ???
val prov = new DatabaseConfigProvider {
def get[P <: BasicProfile] = dc.asInstanceOf[DatabaseConfig[P]]
}
因为看起来丑陋asInstanceOf
。
方法的输出类型get
由调用方定义。您添加了类型界限(如T <: Profile
),但这仅意味着对调用者的限制。如果调用方要求您提供另一种类型的子类型,则任何类型的转换(如您所做的那样)都会在运行时失败Profile
。
如果您提供有关期望得到的结果的更多详细信息,我可以提供具体建议,以扩大答案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句