【发布时间】:2018-03-19 22:34:09
【问题描述】:
我在 Scala 中经常遇到以下问题:
给定一个特征
trait Foo { def foo: String }
和一个参数化的类
case class Bar[T <: Foo](t: T)
我想编写一个与 Bar 一起工作的方法,而不需要复制类型约束,例如:
def doSth(bar: Bar[_]) = bar.t.foo
不幸的是,它没有编译,我需要写:
def doSth[T <: Foo](bar: Bar[T]) = bar.t.foo
为什么编译器不能推断如果我有一个Bar[_],那么_ 必须是一个Foo?
是否有解决方法(抽象类型会避免重复,但会增加表示某些约束的复杂性)?
【问题讨论】: