简体   繁体   中英

Scala Return type missmatch

Using this code:

val kv: HashMap[Int, Double] = HashMap[Int, Double]()
val temp = valuesList.list.foreach { (id: Int, value: Option[Double]) => 
  val kvValue: Double = kv.getOrElse(id, 0)
  val nvValue: Double = value.getOrElse(0)
  val nv = kvValue + nvValue
  kv.put(id, nv)
}

I get this error:

type mismatch;
 found   : (Int, Option[Double]) => Option[Double]
 required: ((Int, Option[Double])) => ?

Can't seem to find the solution...

I guess you give the wrong type of your function.

The valuesList is probably a list of tuple. That is, List[(Int, Option[Double])] .

So the foreach gives the tuple to your anonymous function, rather than a Int and a Option .

A quick solution is using case to construct a partial function which nudges compiler to unpack tuple for you.

import scala.collection.mutable.HashMap

val kv: HashMap[Int, Double] = HashMap[Int, Double]()
val valuesList = List(1-> Option(1.0))

val temp = valuesList foreach {
  case (id: Int, value: Option[Double]) =>
    val kvValue: Double = kv.getOrElse(id, 0)
    val nvValue: Double = value.getOrElse(0)
    val nv = kvValue + nvValue
    kv.put(id, nv)
}

println(kv)
// gives Map(1 -> 1.0)

Make sure I changed valuesList here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM