Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScalaIDE - a strangeness of a method that ends with colon

I have come to an idea that in order to create a prefix method for an object, I could use : at te end of the method name, hence, I wrote:

def aaa: {
}

and it compiles just fine! However, this is of no use, so I want to make the method return something, so, uncertain, I write:

def aaa: = {
}

error!

- identifier expected but '=' found.
- not found: type <error>

Ok, I understand that the compiler breaks at : =, I become curious and I try:

def aaa: {
  println("wow")
}

error again!

illegal start of declaration (possible cause: missing `=' in front of current method body)

Then I try this:

val a = aaa

and it says (hovering over aaa) that aaa signature is def aaa: AnyRef, so I try:

def aaa: {
  Global
}

where Global is an object. Still error. So, my question is: why this syntax is allowed? I can't make it work like a prefix method, I can't use this method for side-effects and I can't make it return anything. Why does it allow me to write like this in the first place?

UPDATE:

now I try this:

def aaa: {} = {
  Global
}

and it works. So looks like that {} denotes AnyRef. Starts feeling like I am in the JavaScript wonderland.

like image 868
noncom Avatar asked Jan 16 '23 14:01

noncom


1 Answers

You get these error, because a colon at the end of a method name means, that you'd like to specify a return type. If you then don't give one, the compiler complains. With {} it works, because you give a type, in this case an empty structural type, which is basically the same as AnyRef. There are rules, when you are actually allowed to add a colon at the end of a method name, afaik the method can only consist of non-alphanumeric characters. So def +:(x:Int) is ok, def foo:(x:Int) leads to an error. But I'm not quiet sure about that. Also methods that end with a colon are right-associative.

like image 61
drexin Avatar answered Jan 27 '23 23:01

drexin