An expression is all that can be evaluated to get a value. When an operator is evaluated, it causes side effects, but does not come down to value.
A useful rule of thumb is that if you can put it to the right of the assignment, it is an expression.
val x = (anything legal here must be an expression)
If you cannot put it on the right side of the assignment, this is probably a statement. For example, none of them is valid, because the bits on the right are operators:
val x = import scala.collection.mutable
Scala, like many functional first languages, has very few “clean” statements. Instead, many of the constructs that people think of (and call them) are expressions that evaluate Unit :
scala> val x = print("hello world") // a "print statement" is actually an expression x: Unit = () scala> val x = for (i in Array(1, 2, 3)) println("Hello " + i) // for loops are expressions too! x: Unit = ()
Processing the words “if” as expressions is actually very convenient:
val meal = if (hungry) Some(food) else None
tl; dr: The technical difference between an operator and an expression is that the expression evaluates the value, but the operator does not. Informally, many people use the term “statement” to mean something that is evaluated only for side effects, but many of these “statements” are actually expressions that are rated as Unit .
n8gray
source share