scala类型系统:14) multiple bounds

在之前的:scala类型系统:11) upper bounds & lower bounds 结尾提到过在multiple bounds(多重界定)情况下java与scala的一些差异,这篇详细说一下scala里的multiple bounds。

1 不能同时有多个upper bounds 或 lower bounds,变通的方式是使用复合类型
T <: A with B

T >: A with B
2 可以同时有upper bounds 和 lower bounds,如
T >: A <: B

这种情况 lower bounds 必须写在前边,upper bounds写在后边,位置不能反。同时A要符合B的子类型,A与B不能是两个无关的类型。

3 可以同时有多个view bounds
T <% A <% B

这种情况要求必须同时存在 T=>A的隐式转换,和T=>B的隐式转换。

scala> implicit def string2A(s:String) = new A
scala> implicit def string2B(s:String) = new B

scala> def foo[ T <% A <% B](x:T)  = println("OK")

scala> foo("test")
OK
4 可以同时有多个context bounds
T : A : B

这种情况要求必须同时存在A[T]类型的隐式值,和B[T]类型的隐式值。

scala> class A[T];
scala> class B[T];

scala> implicit val a = new A[Int]
scala> implicit val b = new B[Int]

scala> def foo[ T : A : B ](i:T) = println("OK")

scala> foo(2)
OK

发表评论

电子邮件地址不会被公开。 必填项已用*标注