MaxK
MaxK

Reputation: 625

Why calling a function like this works in Scala?

I have the following Scala code snippet:

type Set = Int => Boolean

def contains(s: Set, element:Int): Boolean = s(element)

def singletonSet(element: Int): Set = Set(element)

val oneElementSet = singletonSet(5)

contains(oneElementSet, 5) // true
contains(oneElementSet, 6) // false

I'm trying to wrap my head around what this does: Set(element). Looks like it'll substitute element in place of an Int argument, to produce this: 5 => Boolean. There is no comparison anywhere, so why does oneElementSet(5) returns true, and oneElementSet(6) returns false?

Thanks!

Upvotes: 3

Views: 83

Answers (1)

wingedsubmariner
wingedsubmariner

Reputation: 13667

Scala has separate namespaces for types and values. Your type alias defines what Set is in the type namespace, but in the definition of singletonSet Set comes from the value namespace, in fact it is the companion object scala.collection.immutable.Set. Set(element) invokes the apply method of the companion object, which returns a scala.collection.immutable.Set[Int], which turns out to be a subtype of Int => Boolean and therefore is a Set (your type alias) as well.

Upvotes: 2

Related Questions