我使用Scala类型进行了一些实验
并尝试做类似的事情:
case class Foo(name: String)
defined class Foo
scala> case class Bar(id: Int)
defined class Bar
scala> def process[A <: Foo with Bar](x: A) = println(x)
process: [T <: Foo with Bar](x: T)Unit
试图运行此:
scala> process[Foo](Foo("test"))
<console>:15: error: type arguments [Foo] do not conform to method process's type parameter bounds [T <: Foo with Bar]
process[Foo](Foo("test"))
scala> process[Bar](Bar(1))
<console>:15: error: type arguments [Bar] do not conform to method process's type parameter bounds [T <: Foo with Bar]
process[Bar](Bar(1))
如何在不添加特征的情况下正确执行此操作?
trait Printable
class Foo extends Printable
class Bar extends Printable
def process(x: Printable) = println(x)
不是这样。还有其他方法吗?