0

我用 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)

不是这样的。还有其他一些方法吗?

4

0 回答 0