Reputation: 448
when debugging I had to inspect the scala.collection.GenSetLike file. I encountered this little bit of code in the interface:
trait GenSetLike[A, +Repr]
extends GenIterableLike[A, Repr]
with (A => Boolean)
with Equals
with Parallelizable[A, parallel.ParSet[A]] {
...
}
What does this (A => Boolean)
mix means? I tried searching with various keywords but could not find something satisfactory.
This syntax indicated a function that takes an A and returns a Boolean, but I can't see the meaning in the trait mixin context...
My first guess was that is related to stuff like constructor or apply
, but this is just an intuition.
Please teach me!
Upvotes: 2
Views: 130
Reputation: 3285
Set
in Scala implements Function1[A, Boolean]
(A => Boolean
) interface overriding apply
to be same as contains
, so sets in Scala can be used as functions.
> val s = Set(1,2,3)
s: Set[Int] = Set(1, 2, 3)
> s(2)
res1: Boolean = true
> s.apply(3)
res2: Boolean = true
> s(23)
res3: Boolean = false
This is, btw, the reason why Set is invariant.
Upvotes: 1
Reputation: 14825
A => Boolean
is the syntactic sugar for Function1
trait
scala> def f[A] = (a: A) => true
f: [A]=> A => Boolean
The above lambda can also be written as
scala> def f[A]: Function1[A, Boolean] = (a: A) => true
f: [A]=> A => Boolean
Upvotes: 1