JamieP
JamieP

Reputation: 1794

SCALA Creating Functions Syntax

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?

Upvotes: 2

Views: 164

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

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?).

(new is omitted because of implicit call to apply method right?)

Yes, kind of. List.apply constructs the List and returns it to your method.

def index = List {} creates a method called index that creates a new List by calling List.apply.

Can someone explain, in simple terms (if possible), the difference between the use of {} and () in creating functions and also what Nothing represents?

The empty curly braces {} represent an anonymous function, rather than a simple list of elements. For example I can do:

scala> def index = List {val a = 1; a}
index: List[Int]

Your method is equivalent to (where the parentheses are omitted):

def index = List({})

The result of the anonymous function is passed to apply. When the braces are empty, the return type of the anonymous function is Unit. So we get List[Unit].

def index = List () always returns an empty List. However, because you have no annotations, the compiler cannot infer a type from this, so it is inferred as Nothing, which is a sub-type of every other type. This allows us to combine a List[Nothing] with a List[Int] and still compile.

I see that Unit (equivalent to null in Java?) ...

Unit is the return type of a method that doesn't return anything. Similar to void in Java, not null.

Upvotes: 5

Related Questions