Reputation: 555
I try to use trailing underscore in Scala function parameter name to avoid clash with keyword type
, but get error:
Welcome to Scala 2.13.1 (Java HotSpot(TM) 64-Bit Server VM, Java 11.0.1).
Type in expressions for evaluation. Or try :help.
scala> def foo(type_: Char): Char = type_
^
error: ':' expected but identifier found.
scala>
I read several explanations about use of underscore in Scala, but none of them mention my case
Upvotes: 1
Views: 156
Reputation: 369420
The usage of the underscore that is relevant in your case, is separating alphanumeric and operator characters in an identifier. If you want to mix alphanumeric characters and operator characters in an identifier, they have to be separated by an underscore, e.g. foo?
is not a legal identifier, but foo_?
is.
By the same logic, type_:
is a valid identifier, and that is how your code is interpreted.
Upvotes: 4
Reputation: 27535
I believe this is a result of a lexer considering type_:
as a valid parameter name, and parser obtaining type_:
identifier followed by Char
type.
In Scala it is valid to have :
as part of the name (e.g. ::
, +:
, :+
), (though this has some restictions what can and what cannot be combined with :
), so to make it possible to distinguish when :
is used as such and when not, compiler uses whitespaces (or other characters that cannot be used in identifier, like brackets) between identifier and type ascription. This whitespace is not needed if there is no ambiguity, but in cases like your you would have to write it as:
def foo(type_ : Char): Char = type_
or the compiler will assume you wanted to write:
def foo(type_: : Char): Char = type_:
typez: Char
apparently isn't producing this ambiguity, as typez:
isn't a valid identifier, same with type0: Char
and type0:
, etc. and it wouldn't compile (unless you used backticks which allows usage of almost any name). However, type_:
IS a valid identifier, so the ambiguity appears, and you have to resolve it manuall with some indentation.
Upvotes: 7