gpt4 book ai didi

包含混合类型值的 Scala 映射

转载 作者:行者123 更新时间:2023-12-04 16:32:22 28 4
gpt4 key购买 nike

我有一个返回的函数(常规代码)

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

在 Scala 中,我将上面更改为 Scala Map,但随后我被迫将其声明为
Map[String, Any]

但这有一个缺点,如果我访问诸如
map (“单词”)
我必须添加样板
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", 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

我更喜欢 case 类,因为字段是命名的,而且实际上只是多一行。

关于包含混合类型值的 Scala 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6584840/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com