I'm trying to understand why I need to specify the specific enum type I'm using to be able to use the "match type" feature of scala 3.
val doesntCompile: String = testTypeMatch(FieldType.Text)
val compile: String = testTypeMatch[FieldType.Text.type](FieldType.Text)
def testTypeMatch[T <: FieldType](fieldType: T): Elem[T] =
fieldType match
case _: FieldType.Text.type => "randomString"
case _: FieldType.Number.type => 55
type Elem[x <: FieldType] = x match
case FieldType.Text.type => String
case FieldType.Number.type => Int
enum FieldType {
case Text
case Number
}
Without hardcoding [FieldType.Text.type] I'm getting a compilation error.
I've tried the same with sealed trait and it worked fine, specifying the type was not needed
sealed trait FieldType
object FieldType{
case object Text extends FieldType
case object Number extends FieldType
}
The inferred type of
FieldType.TextisFieldType, notFieldType.Text.type.Analogously, for the enum
the expression
Foo.Barwill have the typeFooby default (try it out in the repl), similarly to how"hello"has the typeStringand not the singleton type"hello".Demoting the
FieldTypeto a marker trait solves the issue:I must admit that I'm not so sure whether this is the most idiomatic way to do it, though; The
enumkeyword was supposed to replacesealed traits, but this seems to be one of those cases wheresealed traits behave quite differently from theenums.