"WeatherReading"はcaseクラス "WeatherReadingStub"のオブジェクトであるのに対し、[readStock]という関数は[String、WeatherReading]型の値を返す必要があります。私は、関数 "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のオブジェクトです"とは、コンパニオンオブジェクトを意味しますか?コンパニオンオブジェクトはクラスと同じ名前を持ち、「ケースクラス」は自動的に独自のコンパニオンオブジェクトを作成します。 – jwvh
[これらの有益なガイドライン](http://stackoverflow.com/help/mcve)に従うと、あなたの質問に対するより迅速で迅速な回答が得られます。また、コードを書式設定して左右にスクロールする必要がないようにすると便利です。 – jwvh