#scala #pattern-matching #type-inference #type-safety #aux-pattern
#scala #сопоставление шаблонов #вывод типа #безопасность типов #вспомогательный шаблон
Вопрос:
Рассмотрим:
sealed trait A
case object B extends A
case object C extends A
case object D extends A
sealed trait Test {
type AA <: A
val aa: AA
}
object Test {
type Aux[AAA <: A] = Test { type AA = AAA }
}
def compilesOk(t: Test) = t.aa match {
case _: B.type =>
println("B")
case _: C.type =>
println("C")
case _: D.type =>
println("D")
}
def compileError(t: Test) = t.aa match {
case B => println("B")
case C => println("C")
case D => println("D")
}
compileError
Функция не может скомпилироваться со следующей ошибкой:
Error:(47, 10) pattern type is incompatible with expected type;
found : B.type
required: t.AA
case B => println("B")
Error:(48, 10) pattern type is incompatible with expected type;
found : C.type
required: t.AA
case C => println("C")
Error:(49, 10) pattern type is incompatible with expected type;
found : D.type
required: t.AA
case D => println("D")
Я не совсем понимаю ошибку несовместимости. Все B
, C
и D
являются экземплярами A
, что с этим не так и почему compilesOk
функция компилируется нормально?
Комментарии:
1. В Scala 3 это компилирует scastie.scala-lang.org/fYDwivfETF2GknlRUsHUig
2. @DmytroMitin Выглядит как еще один пробел в семантике типа-члена в Scala 2. Спасибо.