n.Ken n.Ken - 1 year ago 110
Scala Question

calculate the avg of Option Int with scala

I'm new to scala and I have a listbuffer in a map with this structure :

ListBuffer(Note(test@gmail.com,Some(2)), Note(test@gmail.com,Some(3)))

I want to calculate the avg of (Some(2),Some(3))
when i calculate the sum i get this error
Overloaded method value [+] cannot be applied to (Any)

var sum = 0
for (note <- notes)
sum += note.note.getOrElse("existe")

Answer Source

You have note property as Option[Int]. When you call getOrElse(String) compiler figure out result type as Any, the closest superclass of Int and String. As you know, Any doesn't have + method.

You may refactor your code in following way:

val numbers = notes.flatMap(_.note) // or notes.map(_.note.getOrElse(0)) if you want to consider empty notes

numbers.sum / numbers.length
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download