Get versus direct access on Maps in Scala

I know I haven’t posted in a while, I’m going to try to post more often.  I’ll make a relevant post soon about what I’ve been up to.  For now, I want to talk about Scala.

I’ve been learning Scala, it’s a great little programming language.  I would like to see java replaced by it eventually.

I was dealing with a very specific issue in scala, whereby I was matching a Map and getting the following error:

error: constructor cannot be instantiated to expected type;
[scalac]  found   : Some[A]
[scalac]  required: Int
[scalac]           case Some(x) => {

It turns out, there are two ways to access a Map.  So if I have

val wallet = Map(”Money” -> 100)

wallet(”Money”) returns 100

wallet(”Monkey”) throws an exception

wallet.get(”Money”) returns Some(100)

wallet.get(”Monkey”) returns None

Therefore, I was supposed to be using get when matching access to wallet:

val numOfM= wallet.get(”Monkey”)

numOfM match {

Some(num) => {println “#:” + num}

None => {println “You don’t have enough bananas :(”}

}

Leave a Reply