Yesterday i saw that Scala 3.2.2 appeared on Maven. After some playing around i observed something strange. Take the code:
trait Trait :
type Y
var list: List[Y] = Nil
class Class extends Trait:
type Y = Int
def add(elm: Y): Unit = list = elm :: list
object Object extends Class :
add(42)
println(Object.list)
Which works in both Scala 3.2.1 and 3.2.2 and produces the expected result. In Scala 3.2.1 the type Y
must be defined at member level, but in 3.2.2 this also works:
trait Trait :
type Y
var list: List[Y] = Nil
class Class[Y] extends Trait:
def add(elm: Y): Unit = list = elm :: list
object Object extends Class[Int] :
add(42)
println(Object.list)
In Scala 3.2.1 this given a compiler error:
[error] -- [E007] Type Mismatch Error: ...
[error] 66 | def add(elm: Y): Unit = list = elm :: list
[error] | ^^^
[error] | Found: (elm : Y)
[error] | Required: Class.this.Y²
[error] |
[error] | where: Y is a type in class Class
[error] | Y² is a type in trait Trait
Nice, you can define a type member via the parameter! This is an improvement i think, and reduces the number of types and type copying. However … if you now make Y
a subtype of String
in the trait, like this:
trait Trait :
type Y <: String
var list: List[Y] = Nil
class Class[Y] extends Trait:
def add(elm: Y): Unit = list = elm :: list
object Object extends Class[Int] :
add(42)
println(Object.list)
this still compiles and produces List(42)
when executed ??? Btw, when you convert back to type member level:
trait Trait :
type Y <: String
var list: List[Y] = Nil
class Class extends Trait:
type Y = Int
def add(elm: Y): Unit = list = elm :: list
object Object extends Class :
add(42)
println(Object.list)
the code is not accepted by the Scala 3.2.2 compiler:
[error] -- [E163] Declaration Error: ...
[error] 95 | type Y = Int
[error] | ^
[error] | error overriding type Y in trait Trait with bounds <: String;
[error] | type Y, which equals Int has incompatible type
I am missing something or is this just plain wrong?