Im a Scala newbie and I get that its a really rich language. One thing that is getting me caught out syntax-wise is on function creation. I understand that braces {} are interpreted by the compiler as being synonymous with parentheses () in many contexts, but the following I still do not quite understand.
The following is the output from Scala REPL:
scala> def index = List {}
index: List[Unit]
scala> def index = List ()
index: List[Nothing]
Q1.
If I understand the above correctly, I am creating a function called index
that creates a new List (new
is omitted because of implicit call to apply
method right?).
I see that Unit
(equivalent to null
in Java?) is the Type of my List when braces {} are used. But Nothing is the type when using parens ().
Q2.
Can someone explain, in simple terms (if possible), the difference between the use of {}
and ()
in creating functions and also what Nothing
represents?
Edit - So the following are equivalent?
def index = List {val a = 1; a}
def index = List ({val a = 1; a})
Im also struggling a bit with where the terms function
and method
seem to be used interchangeably.
Is it correct to say that both the above can both be considered either a function
or method
?
Or does it depend on who you talk to?