I've just seen I can do:
Set(1, 2, 3).map(Set(1))
which yields the result:
Set(true, false)
But I thought that the map function can only take another function not a new Set. If anything I'd expect this to return a set of sets. What's going on and what does the result mean?
map() method is a member of TraversableLike trait, it is used to run a predicate method on each elements of a collection. It returns a new collection.
Solution. Add elements to a mutable map by simply assigning them, or with the += method. Remove elements with -= or --= . Update elements by reassigning them.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
Scala Map get() method with exampleThe get() method is utilized to give the value associated with the keys of the map. The values are returned here as an Option i.e, either in form of Some or None. Return Type: It returns the keys corresponding to the values given in the method as argument.
But I thought that the
map
function can only take another function not a newSet
.
A Set
is a function. It is a function from its elements to booleans: when you pass it an element, it tells you whether that element is part of the Set
.
Set(1, 2, 3).map(Set(1))
Iterates over the Set(1, 2, 3)
, passing each each element to the Set(1)
. I.e. it first asks "is 1
a member of set {1}
", which is true
, then it asks the same question for 2
and 3
, which is false
.
So, the result is Set(true, false, false)
, which of course is just Set(true, false)
.
Similarly, a sequence is a function from integers to elements, a map is a function from keys to values.
Set
is also function - it extends Function1
. See Inherited section in Scaladoc:
http://www.scala-lang.org/api/current/scala/collection/immutable/Set.html
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