包含混合类型值的Scala映射
发布时间:2020-12-16 09:24:06 所属栏目:安全 来源:网络整理
导读:我有一个返回的函数(groovy代码) [words: "one two",row: 23,col: 45] 在scala中,我将上面更改为scala Map,但后来我被迫将其声明为 Map[String,Any] 但这有一个缺点,即如果我访问一个键,如 图(“字”) 我必须添加样板 map2("words").asInstanceOf[String] 在
我有一个返回的函数(groovy代码)
[words: "one two",row: 23,col: 45] 在scala中,我将上面更改为scala Map,但后来我被迫将其声明为 Map[String,Any] 但这有一个缺点,即如果我访问一个键,如 map2("words").asInstanceOf[String] 在scala中是否有更好的方法不需要我添加asInstanceOf? 解决方法
为了避免转换并从静态类型中受益,您可以返回元组(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 或者为结果使用案例类: case class MyResult(line: String,row: Int,col: Int) def getResult = MyResult("one two",45) val res = getResult res.line // the line // alternatively use the extractor provided by the case class val MyResult(line,_) = getResult // col is discarded line // the line row // the row 我更喜欢case类,因为字段是命名的,它实际上只是一行. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |