Ketan Khairnar
Ketan Khairnar

Reputation: 1630

Scala map example not working as expected

Am doing all the examples from the "Pragmatic Bookshelf Programming Scala" book. It is simple singleton example but am not getting it right i.e. values from map are not fetched. Can you point out the error.

class Marker(val color: String) {
  println("Creating " + this)
  override def toString(): String = "marker color is " + color
}

And singleton MarkerFactory is as below

object MarkerFactory {
  private val markers = new HashMap[String, Marker];
  markers += "red" -> new Marker("red")
  markers += "blue" -> new Marker("blue")
  markers += "green" -> new Marker("green")

  def getMarker(color: String) {
    if (markers.contains(color)) markers(color) else null
  }

  def main(args: Array[String]) {
    println(markers)
    println((MarkerFactory getMarker "red").toString)
    println(MarkerFactory getMarker "blue")
    println(MarkerFactory getMarker "red")
    println(MarkerFactory getMarker "yellow")
  }

}

Am getting output like this.

Creating marker color is red
Creating marker color is blue
Creating marker color is green
Map(green -> marker color is green, red -> marker color is red, blue -> marker color is blue)
()
()
()
()

Upvotes: 2

Views: 2223

Answers (1)

Ken Bloom
Ken Bloom

Reputation: 58770

Using an open brace without an equals sign is cryptic shorthand for a method that returns Unit. ( () is the only valid value of a Unit, and that's why your code prints ().)

def getMarker(color: String) {
  if (markers.contains(color)) markers(color) else null
}

Change it to

def getMarker(color: String)  = {
  if (markers.contains(color)) markers(color) else null
}

Or better yet

def getMarker(color: String) = markers.getOrElse(color,null)

Upvotes: 10

Related Questions