gpt4 book ai didi

Scala - value < 不是 AnyVal 的成员

转载 作者:行者123 更新时间:2023-12-04 16:57:35 24 4
gpt4 key购买 nike

这是我的代码。我在第二个 case 子句中遇到编译错误:

Error:(92, 26) value < is not a member of AnyVal case x if x._2 < 2 => "price under 2"


def tupleMatch: Unit = {
val donut = Tuple2("Donut", 2.5)
val plain = Tuple2("Plain", 1.0)
val tuples = List(donut, plain)
tuples.foreach { tuple =>
val toPrint = tuple match {
case ("Donut", price) => s"price of Donut is ${donut._2}"
case (_, price) if price < 2 => "price under 2"
case _ => "other"
}
println(toPrint)

}
}

我改变后
val plain = Tuple2("Plain", 1)


val plain = Tuple2("Plain", 1.0)

它终于起作用了。
这让我很困惑,我想知道为什么?

最佳答案

那是因为您的元组数组由两种不同的类型组成:Tuple2[String, Int]Tuple2[String, Double] .这些类型由编译器推断,然后元组数组的干扰类型是 Tuple2[String, AnyVal] .当您放置 Double 表示时,编译器能够创建 Tuple2[String, Double] .

关于Scala - value < 不是 AnyVal 的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53335311/

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