Reputation: 80192
What's the verbose way for val Singleton4 : Set = set => set == 4
? I am unable to understand where the set
parameter is coming from.
Upvotes: 0
Views: 104
Reputation: 74779
The other answers are very good, but I thought I'd throw some additional details to help newcomers to Scala understand the notation better (as there are some hidden gems in the notation that were not uncovered/described).
Let's play the Scala compiler game!
The following val
says enough about what Set
the type represents.
val Singleton4: Set = set => set == 4
The type of val
is given explicitly - it's Set
. We don't however know much about it...yet. It has however to be given to the compiler before it can be used and given the left-hand side it's a function (mind the =>
two-letter string) from a type (we'll get to it in a moment) to Boolean
since set == 4
will inevitably end as Boolean
.
From set == 4
we can deduce that set
can only be Int
(so you can compare apples to apples) and hence we've got the type of set
as Int
.
The right-hand side of =
of the val
could also have been written as:
val Singleton4: Set = (set: Int) => set == 4
So, the Singleton4
val is an instance of a function Int => Boolean
that's called Set
. Set
's declared as such somewhere above (lexicographically):
type Set = Int => Boolean
You could substitute Set
to the type alias and end up with:
val Singleton4: Int => Boolean = (set: Int) => set == 4
Upvotes: 0
Reputation: 26739
What maybe confuses you is the fact that Set
is not what one would expect from the Scala library. You should read the line as:
val Singleton4: Int => Boolean = someArbitraryName => someArbitraryName == 4
// <identifier> <type> = <argument> => <returnValue>
Upvotes: 3
Reputation: 15783
It's not "coming" from anywhere, Set
is defined as a function from an integer to a boolean and the type of Singleton4
is exactly that, it takes an integer and returns a function which needs another integer and returns a boolean:
scala> type Set = Int => Boolean
defined type alias Set
scala> def singletonSet(elem: Int): Set = set => set == elem
singletonSet: (elem: Int)Int => Boolean
scala> val p: Set = singletonSet(3)
p: Int => Boolean = <function1>
So now p
is a function which takes an integer:
scala> p(3)
res0: Boolean = true
scala> p(2)
res1: Boolean = false
An alternative way of writing that is this:
def singletonSet(elem: Int) = (i: Int) => i == elem
val p: (Int) => Boolean = singletonSet(3)
Or using a different way but achieving the same result:
def singletonSet(elem: Int)(i: Int): Boolean = i == elem
val p: (Int) => Boolean = singletonSet2(3)
By currying the function and applying only one argument you get back a function which still needs another integer to be fully evaluated.
Upvotes: 2