【发布时间】:2018-02-28 07:34:21
【问题描述】:
为什么 Scala 编译器无法编译 next code:
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,不是吗?
更新:
我想用确切的类型实现这个 trait DatabaseConfigProvider 并以这种方式进行:
val dc: DatabaseConfig[JdbcProfile] = ???
val prov = new DatabaseConfigProvider {
def get[P <: BasicProfile] = dc.asInstanceOf[DatabaseConfig[P]]
}
因为asInstanceOf而看起来很丑。
【问题讨论】:
-
你能说明是哪一行导致了错误吗?
标签: scala types generic-programming scala-generics