I do not understand why Set
defined in this way produces these results.
My understanding is that Set
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
}
There are nine predefined value types and they are non-null able: Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean. Scala has both numeric (e.g., Int and Double) and non-numeric types (e.g., String) that can be used to define values and variables.
Since ++ generally represents concatenation of two collections, ++= would mean an "in place" update of a collection with another collection by concatenating the second collection to the first.
Scala type hierarchy. Any is the supertype of all types, also called the top type. It defines certain universal methods such as equals , hashCode , and toString . The top-type Any has a subtype Matchable , which is used to mark all types that we can perform pattern matching on.
I agree what izstas said they are different things. But "type Set = Int => Boolean" has effect. In the following steps in scala console, after "type Set = Int => Boolean" the error disappears.
scala> def func(s:Set) = 1
<console>:10: error: type Set takes type parameters
def func(s:Set) = 1
^
scala> def func(s:Set[Int]) = 1
func: (s: Set[Int])Int <---- specify the type in the set
scala> type Set = Int => Boolean
defined type alias Set
scala> def func(s:Set) = 1 <---- no error
func: (s: Set)Int
scala> def getSet(s:Set) = s
getSet: (s: Set)Set
scala> getSet(Set(1,2))
res0: Set = Set(1, 2)
scala> Set(1,2)
res1: scala.collection.immutable.Set[Int] = Set(1, 2)
scala> val t=Set(1,2)
t: scala.collection.immutable.Set[Int] = Set(1, 2)
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
: http://www.scala-lang.org/api/2.10.3/index.html#scala.collection.immutable.Set
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With