为什么 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
.