Scala 编译器抱怨方法级别的泛型参数类型不匹配

Scala compiler is complaining about type mismatch for generic parameter on method level

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

但是SomeProfileT,不是吗?

更新:

我想用确切的类型实现这个特性 DatabaseConfigProvider 并以这种方式实现:

val dc: DatabaseConfig[JdbcProfile] = ???
val prov = new DatabaseConfigProvider {
  def get[P <: BasicProfile] = dc.asInstanceOf[DatabaseConfig[P]]
}

因为 asInstanceOf.

看起来很难看

您错误地声明了输入参数。尝试以下:

trait Profile {}
class SomeProfile() extends Profile

trait Foo {
  def get[T >: Profile]: Option[T]
}

object Example {
  val foo2: Foo = new Foo {
    override def get[T >: Profile]: Option[T] = Some(new SomeProfile())
  }
}

关于 :> 作用的解释,您可以在 Whosebug 中轻松找到(例如:What does [B >: A] do in Scala?

您的方法的输出类型 get 由调用者定义。您添加了类型界限(如 T <: Profile),但这仅意味着对调用者的限制。如果调用者要求 Profile 的另一种子类型而不是您所铸造的子类型,则任何类型转换(就像您所做的那样)都将在运行时失败。

如果您提供更多关于您期望得到的结果的详细信息,我可以扩展答案并提供具体的建议如何获得它。