1

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

但是,不是吗SomeProfileT

更新:

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

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

看起来很丑,因为asInstanceOf.

4

2 回答 2

2

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

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())
  }
}

:>您可以在 Stackoverflow 中轻松找到有关功能的说明(例如: [B >: A] 在 Scala 中做什么?

于 2018-02-28T07:40:43.837 回答
1

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

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

于 2018-02-28T07:53:59.010 回答