Rajeun
Rajeun

Reputation: 721

type mismatch; found : List[Double.type] required: List[Double]

I'm trying to calculate average in scala this is my function average:

  def average(list: List[Double]): Double =
    list.foldLeft(0.0)(_ + _) / list.foldLeft(0.0)((r, c) => r + 1)

and this is my code:

    var p3 = List(Double)
    for (dimension <- result.dimensions) {
      p3 :+ dimension.average
    }
    println(average(p3))

My structure:

{
"result" : {
"dimensions" : [{
"average" : 2.2
},
{
"average" : 4.2
}]
} 
}

Upvotes: 0

Views: 1219

Answers (2)

fxlae
fxlae

Reputation: 905

The initialization of your empty List is wrong. Try the following instead:

var p3 = List[Double]()

Apart from that, you could achieve the same in an easier, more idiomatic way. One way is to use yield:

val p3 = for (dimension <- result.dimensions) yield dimension.average

Which is basically the same as just doing

val p3 = result.dimensions.map(_.average)

Apart from that, your average function is a bit complex, you can compute the average of a list just by doing val avg = list.sum/list.length.

Upvotes: 1

Alexey Romanov
Alexey Romanov

Reputation: 170735

List(Double) is a list containing one element which is the so-called companion object of Double. If you want an empty list of Double, you need List[Double]() (or clearer, List.empty[Double]). Then the next error is that in the p3 :+ dimension.average you create a new List and then do nothing with it. You can fix it by using p3 = p3 :+ dimension.average, but that would be a horrible style.

Upvotes: 1

Related Questions