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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With