Mike
Mike

Reputation: 19697

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)
    }

}

Upvotes: 7

Views: 1647

Answers (4)

Landei
Landei

Reputation: 54574

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

Upvotes: 9

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297155

The closest working code to what you did is this:

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

        println(answer)
    }
}

Upvotes: 4

pedrofurla
pedrofurla

Reputation: 12783

Here is my solution:

scala> val answer = (1 until 10) filter( current => (current % 3 == 0) || (current % 5 == 0)) sum
answer: Int = 23

Notice the filter instead of if's.

Another one in a even more idiomatic Scala:

( for( x <- 1 until 10 if x % 3 == 0 || x % 5 == 0 ) yield x ) sum

Upvotes: 8

Ben Jackson
Ben Jackson

Reputation: 93690

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)

Upvotes: 11

Related Questions