Scala函数子类型

时间:2016-10-28 11:53:54

标签: scala

type Fun1 = { val a: A } => { val b: B }

type Fun2 = { val b: B } => { val a: A }

我想知道的是上述类型的超类型。

Fun1<:Common

Fun2<:Common

1 个答案:

答案 0 :(得分:7)

由于函数的输入类型是逆变,而返回类型是协变,因此常见的输入类型是“最接近”的常见子类型 A和B(例如A with B)和公共返回类型是A和B的“最接近的”超类型(例如Any),所以如果我们对此一无所知A和B,答案是:

A with B => Any

例如:

scala> class A
defined class A

scala> class B
defined class B

scala> type Fun1 = A => B
defined type alias Fun1

scala> type Fun2 = B => A
defined type alias Fun2

scala> val f1: Fun1 = (x: A) => new B()
f1: A => B = <function1>

scala> val f2: Fun2 = (x: B) => new A()
f2: B => A = <function1>

// both f1 and f2 can be assigned into a value of type A with B => Any
scala> val f3: A with B => Any = f1
f3: A with B => Any = <function1>

scala> val f4: A with B => Any = f2
f4: A with B => Any = <function1>