Scala map containing mix type values

后端 未结 4 1342
感情败类
感情败类 2020-12-19 13:21

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 for

4条回答
  •  北海茫月
    2020-12-19 14:01

    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.

提交回复
热议问题