Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala map containing mix type values

Tags:

scala

I have a function that returns ( groovy code)

[words: "one two", row: 23, col: 45]

In scala I change above to scala Map but then I am forced to declare it as

Map[String, Any]

but this has the disadvantage that if I access a key such as map("words") I have to add the boilerplate

map2("words").asInstanceOf[String]

Is there a better way in scala that does not require me to add asInstanceOf?

like image 388
rjc Avatar asked Jul 05 '11 15:07

rjc


1 Answers

In order to avoid the casting and benefit from static-typing, you can either return a tuple (String, Int, Int):

def getResult = ("one two", 23, 45)

val res = getResult
res._1 // the line

// alternatively use the extractor
val (line, row, _) = getResult // col is discarded
line // the line
row  // the row

or use a case class for the result:

case class MyResult(line: String, row: Int, col: Int)

def getResult = MyResult("one two", 23, 45)

val res = getResult
res.line // the line

// alternatively use the extractor provided by the case class
val MyResult(line, row, _) = getResult // col is discarded
line // the line
row  // the row

I would prefer the case class because the fields are named and it's really just one line more.

like image 81
kassens Avatar answered Oct 12 '22 06:10

kassens