使用Scala泛型时发生意外的类型不匹配

时间:2018-11-25 18:35:35

标签: scala generics

我有一个简单的场景,在使用Scala泛型时会产生类型不匹配的情况,目前尚不清楚原因或解决方式。

trait Foo
case class Bar() extends Foo

trait FooGetter[T <: Foo] {
  def get: T = Bar() // Error
}

错误:

  

类型不匹配;发现:   所需栏:T

有任何提示吗?

3 个答案:

答案 0 :(得分:1)

此处T <: Foo表示Foo是类型T上限

enter image description here

如您所见,BarT之间没有关系,因此强制转换不能以隐式方式发生。

当然,如果可以保证投射的安全性,则可以使用asInstanceOf以明确的方式进行投射。

另一方面,当T是父级而Foo是子级时,以下条件很好。

trait FooGetter[T >: Foo] {
  def get: T = Bar()
}

答案 1 :(得分:0)

您可以像这样简化代码:

trait Foo
case class Bar() extends Foo

trait FooGetter {
  def get: Foo = Bar()
}
无论如何,

FooGetterFoo紧密相连,使FooGetter成为通用没有任何意义。 (请注意,Bar是Scala类型检查器的Foo。)

答案 2 :(得分:0)

在您的示例中,始终有效的是asInstanceOf

trait Foo
case class Bar() extends Foo

trait FooGetter[T <: Foo] {
  def get: T = Bar().asInstanceOf[T]
}

这可行:

println(new FooGetter[Bar]{}.get) // Bar()

但是,正如Seth Tisue指出的:

  

如果结果代码不是,根本就没有使用泛型的意义   实际上是通用的。

相关问题