Is everything a function or expression or object in scala?

scala

Solution

I thought everything is expression because the statement returns a value.

There are things that don't have values, but for the most part, this is correct. That means that we can basically drop the distinction between "statement" and "expression" in Scala.

The term "returns a value" is not quite fitting, however. We say everything "evaluates" to a value.

But I also heard that everything is an object in scala.

That doesn't contradict the previous statement at all :) It just means that every possible value is an object (so every expression evaluates to an object). By the way, functions, as first-class citizens in Scala, are objects, too.

Why did scala choose to do it one way or the other?

It has to be noted that this is in fact a generalization of the Java way, where statements and expressions are distinct things and not everything is an object. You can translate every piece of Java code to Scala without a lot of adaptions, but not the other way round. So this design decision makes Scala is in fact more powerful in terms of conciseness and expressiveness.

What does that mean to a scala developer?

It means, for example, that:

- You often don't need `return`, because you can just put the return value as the last expression in a method

- You can exploit the fact that `if` and `case` are expressions to make your code shorter

An example would be:

def mymethod(x: Int) = if (x > 2) "yay!" else "too low!"

// ...
println(mymethod(10))  // => prints "yay!"
println(mymethod(0))   // => prints "too low!"

We can also assign the value of such a compound expression to a variable:

val str = value match {
            case Some(x) => "Result: " + x
            case None    => "Error!"
          }

Problem

I am confused. I thought everything is expression because the statement returns a value. But I also heard that everything is an object in scala. What is it in reality? Why did scala choose to do it one way or the other? What does that mean to a scala developer?

Original source