Home > Enterprise >  Why can't the Scala compiler disambiguate a property called `type`?
Why can't the Scala compiler disambiguate a property called `type`?

Time:05-15

Every day I build another case class and wish I could define a property called type on it, but to do so requires using the highly annoying backtick syntax:

doohick.`type`

I get that type is a keyword, but why can't the compiler distinguish the keyword from the property when this x.y accessor syntax and avoid this syntactic wart?

CodePudding user response:

Because x.type is also a valid syntax in Scala. E.g.

val x = 1
val y: x.type = x //y is defined as the same type as x

CodePudding user response:

SwiftMango's answer and Luis Miguel Mejía Suárez's comment are technically incorrect, or at least insufficient: current x.type is only valid in types, your x.type would be valid in expressions, and the compiler can always tell which parts of code are types and which are expressions. So this wouldn't by itself be any more of a problem than e.g. List meaning different things in expression context (the companion object List) and in type context (the generic trait List).

But then what about val y: x.type.type? Would that be the type of the path x.type or illegal application of .type to a type x.type? If the second, how do you express the first? Why should type be a special case, and would allowing other keywords to be used as property/method names without backticks lead to other problems?

Given answers to these questions, you could propose the change, but I wouldn't expect it to be accepted because the win just doesn't seem that great compared to the effort and future maintenance needed for the compiler.

  • Related