Donbeo Donbeo - 1 year ago 113
Scala Question

Meaning of type Set = Int => Boolean in Scala

I do not understand why

defined in this way produces these results.

My understanding is that
is just a function which takes an int and return boolean.

Can someone explain me why I get this result using set?

I think this is a short way to express the function in Scala but I am new to this language and I do not understand how it works.

object sets {
type Set = Int => Boolean

var a=Set(3) //> a : scala.collection.immutable.Set[Int] = Set(3)
a(2) //> res0: Boolean = false
a(3) //> res1: Boolean = true
a(1) //> res2: Boolean = false

Answer Source

The type you defined in type Set = Int => Boolean and the object you created in var a=Set(3) are actually not connected to each other. Even this works:

scala> type Set = String
defined type alias Set

scala> val a = Set(3)
a: scala.collection.immutable.Set[Int] = Set(3)

When you call Set(3), you call apply method on the object Set. If you add new keyword, it will take your type alias into account:

scala> val b = new Set()
b: String = ""

a(2), a(3), a(1) work because Set[A], actually, does implement A => Boolean function trait and apply method is equivalent to contains:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download