Scala right associative methods

I study Scala and play with the object unapply with the matching. I know that if the name ends with ":", then it becomes the correct associative. However, there seem to be some weird naming restrictions

eg. They are wrong

object cons: { def unapply(value: String): Option[(Char, List[Char])] = ??? } object :_cons_: { def unapply(value: String): Option[(Char, List[Char])] = ??? } 

They are valid

 object cons_: { def unapply(value: String): Option[(Char, List[Char])] = ??? } object >>: { def unapply(value: String): Option[(Char, List[Char])] = ??? } 

Thus, there is some kind of weirdness in mixing alphanumeric characters and characters in identifiers.

So basically, I want to have a descriptive name, i.e. "cons" and still have the correct associativity. Also, I would like my operator to be symmetrical for aesthetic reasons :-), so I don't like cons_:
Is there a way to do something related right without using a colon? Or any other suggestions to achieve this?

:_cons_: seems closest, but for some reason, the identifier cannot begin with ':' and have alphanumeric characters

+4
source share
1 answer

From specification (Section 1.1):

There are three ways to generate an identifier. First, an identifier can start with a letter, followed by an arbitrary sequence of letters and numbers. This may be followed by underscores _ and another line consisting of letters and numbers or operator characters. Secondly, an identifier can begin with an operator symbol, followed by an arbitrary sequence of operator symbols. The previous two forms are called equal identifiers. Finally, an identifier can also be formed by an arbitrary string between backquotes (host systems may impose some restrictions on which strings are legal for identifiers). Then the identifier consists of all characters, excluding the backquotes themselves.

So it looks like you're out of luck - if your identifier starts with : it cannot contain characters without an operator. Please note, however, that you can write the following (which is not intended for any meaningful action - just to demonstrate the syntax):

 scala> class X { def `:cons:`(i: Int) = i } defined class X scala> val x = new X x: X = X@6a665da6 scala> 1 `:cons:` x res1: Int = 1 

The method name still ends with a colon, so you get the desired associativity you are looking for.

+3
source

Source: https://habr.com/ru/post/1494716/


All Articles