Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Scala line return a Unit?

Here's a bit of Scala code to sum the values from 1 to 9 which are divisible by 3 or 5. Why does line 5 return a Unit and not a Boolean type?

object Sample {

    def main(args : Array[String]) {
        val answer = (1 until 10).foldLeft(0) ((result, current) => {
            if ((current % 3 == 0) || (current % 5 == 0)) {
                result + current
            }
        })

        println(answer)
    }

}
like image 626
Mike Avatar asked Oct 28 '10 00:10

Mike


2 Answers

The if expression has a type of Unit because there is no else clause. Thus sometimes it returns nothing (Unit) so the entire expression has type Unit.

(I assume you meant to ask why it didn't return Int, not Boolean)

like image 110
Ben Jackson Avatar answered Oct 17 '22 09:10

Ben Jackson


Can we ever be too idiomatic? YES WE CAN!

Set(3,5).map(k => Set(0 until n by k:_*)).flatten.sum

[Edit]

Daniel's suggestion looks better:

Set(3,5).flatMap(k => 0 until n by k).sum
like image 25
Landei Avatar answered Oct 17 '22 10:10

Landei