未装箱的标记类型安全吗?

Are unboxed tagged types safe?

我最近听说了 scala 中未装箱的标记类型,当我试图了解它的具体工作原理时,我发现这个 question 指出了 scalaz 中实现的问题。修复的后果之一是必须显式解包标记类型:

def bmi(mass: Double @@ Kg, height: Double @@ M): Double =
  Tag.unwrap(mass) / pow(Tag.unwrap(height), 2)

然后我考虑了最初的想法,在那里我可以做这样的事情:

type Tagged[U] = { type Tag = U }
type @@[T, U] = T with Tagged[U]

trait Kilogram
trait Meter
type Kg = Double @@ Kilogram
type M = Double @@ Meter

def bmi(mass: Kg, height: M): Double = mass / pow(height, 2)  

所以现在我想知道之前在 scalaz 中发现的问题是否特定于它的方法,或者简单的实现是否也存在擦除、数组或可变参数方面的问题。问题是我还在学习scala,所以我对它的类型系统的理解很有限,我自己也弄不明白。

从类型安全的角度来看是不安全的。 T @@ UT 的子类型,并且 T @@ U 的实例可以用在任何需要 T 实例的地方,即使它是偶然的。考虑以下

type Tagged[U] = { type Tag = U }
type @@[T, U] = T with Tagged[U]
object Tag {
  def apply[@specialized A, T](a: A): A @@ T = a.asInstanceOf[A @@ T]
}

trait Compare[A] { def compare(a1: A, a2: A): Int }

def useCompare[A: Compare](l: List[A]): Option[A] = 
  l.foldLeft(Option.empty[A])((xs, x) => 
    xs.fold(Some(x))(xxs => 
      if (implicitly[Compare[A]].compare(xxs, x) <= 0) Some(xxs) 
      else Some(x)))

implicit def intCompare: Compare[Int] = new Compare[Int] {
  def compare(a1: Int, a2: Int): Int = 
    a1.compareTo(a2)
}

trait Max
implicit def intCompareMax: Compare[Int @@ Max] = new Compare[Int @@ Max] {
  def compare(a1: Int @@ Max, a2: Int @@ Max): Int = 
    a1.compareTo(a2) * -1
}

scala> val listInts: List[Int] = List(1, 2, 3, 4)
listInts: List[Int] = List(1, 2, 3, 4)

scala> val min = useCompare(listInts)
min: Option[Int] = Some(1)

scala> val listIntMaxs: List[Int @@ Max] = listInts.map(Tag[Int, Max])
listIntMaxs: List[@@[Int,Max]] = List(1, 2, 3, 4)

scala> val max = useCompare(listIntMaxs)
max: Option[@@[Int,Max]] = Some(4)

好的,一切都很好,对吧?这就是 T @@ U 存在的原因。我们希望能够创建一个新类型并为其定义新类型 类。不幸的是,当您的同事出现并执行一些有效的重构并意外破坏您的业务逻辑时,一切都不好。

scala> val max = useCompare(listIntMaxs ::: List.empty[Int])
max: Option[Int] = Some(1)

糟糕

在这种情况下,使用子类型,结合 List[+A] 类型参数的协方差导致了一个错误。 List[Int @@ Max] 可以在需要 List[Int] 的地方替换。