alexandru / scala-best-practices

A collection of Scala best practices
4.39k stars 623 forks source link

2.3 Clarity #46

Closed aemc closed 7 years ago

aemc commented 7 years ago

Hi, I am new to scala and stumbled on this repo. So far its great.

I am trying to replicate the advice found in 2.3 and can't get a working code sample. This part could be more noob friendly if possible.

For example, I created a list

def main(args: Array[String]): Unit = {
    var myList: Array[Double] = Array(1.9, 42.0, 25.0, 11.0)

    // summing all elements java way
    var sum = 0.0
    for (num <- myList) {
        sum += num
    }
    println(sum) // 6.0

    val sum2 = myList.map(_.value).sum // does not work...
    println(sum2)

    val sum3 = myList.foldLeft(0.0)((a, b) => a + b) 
    println(sum3) // 6.0

The value is not recognized by my IDE. Thoughts?

piotrkwiecinski commented 7 years ago

@aemc in your case you don't have to use map as you have primitive values. Sum2 should be just:

    var myList: Array[Double] = Array(1.9, 42.0, 25.0, 11.0)

    // summing all elements java way
    var sum = 0.0
    for (num <- myList) {
        sum += num
    }
    println(sum)

    val sum2 = myList.sum 
    println(sum2)

    case class Person(name: String, age: Int)

    val people: List[Person] = List(Person("Peter", 20), Person("Gal", 21))

    val ages = people.map(_.age).sum
    println(ages)

Here is runnable example https://scalafiddle.io/sf/yWACUuR/0

As you can see map is used when you have more complex structure.

aemc commented 7 years ago

@piotrkwiecinski Thanks!