为什么Scala不跟踪匿名类型?

时间:2016-08-28 21:32:49

标签: scala types type-inference

特别是,这个最小的例子:

trait A[T1, T2] {
  def convert(t1: T1): T2
  def reverse(t2: T2): T1
}

class B extends A[Int, Double]  {
  def convert(i: Int): Double = i.toDouble
  def reverse(i: Double): Int = i.toInt
}

class C extends A[Int, Float] {
  def convert(i: Int): Float = i.toFloat
  def reverse(i: Float): Int = i.toInt
}

val bOrC: A[Int, _] = if (System.nanoTime % 2 == 0) {
  new B
} else {
  new C
}

bOrC.convert(7)
bOrC.reverse(bOrC.convert(7))

最后一行会失败:

scala> bOrC.reverse(bOrC.convert(7))
<console>:12: error: type mismatch;
 found   : (some other)_$1(in value bOrC)
 required: _$1(in value bOrC)
              bOrC.reverse(bOrC.convert(7))

似乎_$1的类型在返回类型和参数中都是相同的 - 它是bOrC的{​​{1}}类型,无论它是什么类型。本地类型推断应该不是问题。为什么我不能这样做?

是否有一种不像以下那样丑陋的解决方法?

T2

编辑:看起来如果你告诉 Scala它是相同的类型,一切都会得到处理。这摆脱了愚蠢的trait A[T1, T2] { def convert(t1: T1): T2 def reverse(t2: X): T1 type X = T2 } // ... rest as before bOrC.reverse(bOrC.convert(7).asInstanceOf[bOrC.X])

type X

1 个答案:

答案 0 :(得分:0)

也许您可以将.red-tape { top: 50px; height: 80px; left: 0; right: 0; top: 70px; background-color: red; position: absolute; } .container { border: 1px solid black; height: 500px; width: 800px; margin: 0 auto; position: relative; } ul { float: right; } ul li { display: inline-block; } 视为类型类,并且只隐式提供A / B中的一个?

C