gpt4 book ai didi

scala - 为什么我的 Scala 类型不匹配?

转载 作者:行者123 更新时间:2023-12-02 07:54:31 25 4
gpt4 key购买 nike

我有以下变量 series:

var series: List[FlotSerie] = List(
new FlotSerie() {
override val label = Full("Min")
},
new FlotSerie() {
override val label = Full("Max")
},
new FlotSerie() {
override val label = Full("Avg")
}
)

不幸的是,我在使用以下方法时遇到编译器错误,该方法采用新的数据点并根据新的 List[FlotSeries] 更新 series数据和旧系列。

def updateSeries(sample: Sample): List[FlotSerie] = {
series = series.map(serie =>
serie match {
case item if item.label == Full("Min") => {
new FlotSerie() {
override val label = item.label
override val data = (sample.timestamp.toDouble, sample.min) :: serie.data
}
}
case item if item.label == Full("Max") => {
new FlotSerie() {
override val label = item.label
override val data = (sample.timestamp.toDouble, sample.max) :: serie.data
}
}
case item if item.label == Full("Avg") => {
new FlotSerie() {
override val label = item.label
override val data = (sample.timestamp.toDouble, sample.avg) :: serie.data
}
}
}
)
}

Scala 编译器在重新分配时阻塞,因为它发现类型不匹配:

error: type mismatch;
found : Unit
required: List[net.liftweb.widgets.flot.FlotSerie]
series = series.map(serie => serie match {

我在这里做错了什么?它似乎应该返回一个可以分配给 series 的 List[FlotSeries]。由于编译器找到了 Unit 我想到了 foreach 总是返回 Unit,我是,但是 match 运算符返回匹配表达式的最后一个值,不是 Unit

最佳答案

Scala 中的赋值返回 Unit(又名 Scala 不完全是 null null),这与 Ruby 不同,Ruby 返回分配的值。您的方法试图返回 Unit 而不是 List[FlotSerie]。

添加:

return series

到您的方法,或将其更改为返回 Unit。

如果合适的话,您还可以使用案例类和适当的匹配来简化您的代码:

  case class FlotSerie(label:Full, data:List[Tuple2[Double, Double]])
var series: List[FlotSerie] = List( FlotSerie(Full("Min"), Nil), FlotSerie(Full("Max"), Nil), FlotSerie(Full("Avg"), Nil) )

def updateSeries(sample: Sample): List[FlotSerie] = {
series = series.map(serie => {
serie.label match {
case Full("Min") => FlotSerie(serie.label, (sample.timestamp.toDouble, sample.min) :: serie.data)
case Full("Max") => FlotSerie(serie.label, (sample.timestamp.toDouble, sample.max) :: serie.data)
case Full("Avg") => FlotSerie(serie.label, (sample.timestamp.toDouble, sample.avg) :: serie.data)
}
})
return series
}

我自己对 Scala 很陌生,所以 YMMV。

关于scala - 为什么我的 Scala 类型不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1677872/

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