开发者

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)
()
()
()
()


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜