Difference between union type LUB and supertype LUB
Asked Answered
S

0

7

List of shapes infers to List[Shape] but list of boxed shapes infers to List[Box[Square | Circle]]

scala> sealed trait Shape
     | case class Square() extends Shape
     | case class Circle() extends Shape
     | case class Box[+T <: Shape](t: T)
     | List(Square(), Circle())
     | List(Box(Square()), Box(Circle()))
val res0: List[Shape & Product & Serializable] = List(Square(), Circle())
val res1: List[Box[Square | Circle]] = List(Box(Square()), Box(Circle()))

Why is res0 not typed to List[Square | Circle] in symmetry with List[Box[Square | Circle]], or vice-versa?

Dotty defines least upper bound in terms of union types

the least upper bound (lub) of a set of types is the union of these types. This replaces the definition of least upper bound in the Scala 2 specification.

What are the rules now for unification relative to this change?

Spring answered 31/5, 2020 at 18:40 Comment(7)
It would certainly make more sense to infer res1 to List[Box[Shape]] in this case, where they both extend a trait and you might want to add Box[Rectangle], etc. later onGherardo
Not sure if this is the only problem, but Box[Square] | Box[Circle] is not a thing because of type erasureGiorgio
@Giorgio Type erasure is irrelevant because type erasure occurs long after typechecking dotty.epfl.ch/docs/internals/overall-structure.html Box[Square] with Box[Circle] exists even in Scala 2.Frayda
@DmytroMitin but how is pattern-matching on Box[Square] | Box[Circle] possible at runtime?Giorgio
@Giorgio You can check this with scalacOptions += "-Xprint:genBCode". Basically it's matched with Box[_] at runtime. But once again this is irrelevant to type inference/typechecking.Frayda
@MarioGalic Quote from guillaume.martres.me/talks/dotty-tutorial/#/1/13 (slide 15 "Type inference and union types"): "By default, Dotty does not infer union types, they are approximated by a non-union supertype. Union types can be "too precise" and prevent legitimate code from compiling"Frayda
@MarioGalic although maybe this is outdatedFrayda

© 2022 - 2024 — McMap. All rights reserved.