페이지

2015년 10월 28일 수요일

Scala2e Chapter3 Next Steps in Scala - Step 10. Use sets and maps

Because Scala aims to help you take advantage of both functional and imperative styles, is collections libraries make a point to differentiate between mutable and immutable collections.

For example, the Scala API contains a base trait for sets, where a trait is similar to Java interface.

Scala the providers two subtraits, on for mutable sets and another for immutable sets.

var jetSet = Set("Boeing", "Airbus")
jetSet += "Lear"
println(jetSet.contains("Cessna"))


To add a new element to a set, you call + on the set, passing in the new element. Both mutable and immutable sets offers a + method, but their behavior differs. 
Whereas a mutable set will add the element to itself, an immutable set will create and return a new set with the element added. 

import scala.collection.mutable.Set

val movieSet = Set("Hitch", "Poltergeist")
movieSet += "Shrek"
println(movieSet)


The mutable set by calling the += method on the set.

import scala.collection.immutable.HashSet

val hashSet = HashSet("Tomatoes", "Chilies")
println(hashSet + "Coriander")




There's base Mat trait in package scala.collection, and two subtrait Maps: a mutable Map in scala.collection.mutable and an immutable one in scala.collection.immutable.

import scala.collection.mutable.Map

val treasureMap = Map[Int, String]()
treasureMap  += (1 -> "Go go island.")
treasureMap  += (2 -> "Find big X on ground.")
treasureMap  += (3 -> "Dig.")

println(treasureMap(2))

The map is empty because you pass nothing to the factory method(the parentheses in "Map[Int, String]()" are empty).
This -> method, which you can invoke on any object in a Scala program, returns a two-element tuple containing the key and value.

If you prefer an immutable map, no import is necessary, as immutable is the default map.

val romanNumeral = Map(
1->"I", 2 ->"II", 3 ->"III", 4->"IIII", 5 ->"IIIII")

println(romanNumeral(4))








댓글 없음: