我有一个名为“readStock”的函数,它应该返回类型为[String,WeatherReading]的值,而“WeatherReading”是案例类“WeatherReadingStub”的对象。我不知道如何声明和返回函数“readStock”的对象。Scala return Map方法的对象类型
代码: -
package HW9
object WeatherStub {
//Setting file name
val fileName = "weather.csv"
//Calling Main
def main(args: Array[String]): Unit = {
val weatherData: Map[String, WeatherReading] = readWeather(fileName)
printWeather(weatherData)
}
def readWeather(fn: String): Map[String,WeatherReading] = {
//Creating a mutable map to collect all the values
val weatherMuteMap = scala.collection.mutable.Map[String, WeatherReading]()
//Checking for empty or null values
def IsEmptyOrNull(s: String): Option[Float] = {
if ((s ne null) && s.trim.length > 0) Some(s.toFloat) else None
}
//Reading file
for (line <- io.Source.fromFile(fn).getLines()) {
val list1 = line.split(",", -1).map(_.trim).toList
//Setting up default values
val TotalPrecp: Option[Float] = IsEmptyOrNull(list1(1).toString) match { case Some(i) => Some(i) case _ => None}
val LowPrecp: Option[Float] = IsEmptyOrNull(list1(2).toString) match { case Some(i) => Some(i) case _ => None}
val HighPrecp: Option[Float] = IsEmptyOrNull(list1(3).toString) match { case Some(i) => Some(i) case _ => None}
//Creating object for the case class WeatherReadingStub
val WeatherReading = WeatherReadingStub(TotalPrecp,LowPrecp,HighPrecp)
//Adding elements to the mutable list
weatherMuteMap(list1(0).toString) = WeatherReading.toString
}
//Converting to Immutbale Map
weatherMuteMap.toMap
}
def printWeather(weatherMap: Map[String, String]): Unit = {
//Format of the message to be printed
println("(Date,{Precipitation,LowTemperature,HighTemperature})\tAverageTemperature")
//Printing the average temp values calculated in Case Class using object
weatherMap.toSeq.sortBy(_._1).foreach(wd => println(wd + "\t" + wd._2.averageTemperature.getOrElse("N/A")))
println
}
}
案例类代码: -
package HW9
case class WeatherReadingStub(precipitation: Option[Float], lowTemperature: Option[Float], highTemperature: Option[Float]) {
def averageTemperature: Option[Float] = (lowTemperature, highTemperature) match {case (Some(i),Some(j)) => Some((i + j)/2) case _ => None}
override def toString: String = s"{${precipitation.getOrElse("MISSING")},${lowTemperature.getOrElse("MISSING")},${highTemperature.getOrElse("MISSING")}}"
}
通过类型[String,WeatherReading]的值'你是指一个元组吗? – mfirry
“WeatherReading是案例类WeatherReadingStub的对象”,你的意思是伴侣对象吗? Companion对象与类名称相同,而'case class'自动创建自己的伴随对象。 – jwvh
如果您遵循[这些有用的指导方针](http://stackoverflow.com/help/mcve),您会更好,更快地回答您的问题。如果您设置代码的格式,以便我们不必左右滚动来阅读它,这也会很有帮助。 – jwvh