Scala If / else statement


#1

Here is a tiny, simple if statement. I am curious as to why Scala does not just return the Some(hello) below in the first if since it is true? Why are braces and an “else” required ? I am sure that a Scala expert in here has a formal explanation.

  def testIf(hello: String): Option[String] = {
    
    if ( true ) {
      Some(hello)
    }
    
    println("oops")
    Some("oops")
  }

#2

It’s not an if statement :slight_smile: It’s an if expression, that means it evaluates to a value. The return value of a Scala method is always the last evaluated expression in the method body, so by evaluating the if expression earlier, you are effectively ignoring it. You’ll need to understand the static typing rules for Scala if expressions to understand exactly how and why it works.

Here’s an explanation of how the if expression works: https://stackoverflow.com/a/45619516/20371

Here’s a style guide that explains when to use curly braces or not: https://docs.scala-lang.org/style/control-structures.html


#3

Your method has three expressions:

  1. if (true) Some("hello")
  2. println("oops")
  3. Some("oops")

It returns the evaluation of the last expression, which is 3.

The first expression is an if without an else, which is syntactic sugar for if (true) Some("hello") else ()

as you can see, that’s not really well typed, the else branch is Unit while the if branch is Some[String], and that can’t unify to anything better than Any, but that’s what it is.


#4

oh thanks … yea … the functional aspect of Scala always throws Java Developers For a Loop … haha
Typical Java Guy Will think this:
if ( true )
value
should cause execution of control to behave like a return statement there .
However, it is logical that it is simply an expression and that the , as you say, last expression represents the value of the function.


#5

thanks … I fully understand it now. I think I had observed that in the past while studying that book, Programming In Scala. But then I stopped studying the syntax and forgot … haha. It is very difficult to try to acquire good skill in multiple languages … Especially if one of the languages is Scala. I am going to have t review that Odersky book again soon.


#6

To be honest, Scala is a tough language to learn. It combines functional with object-oriented and that complexity pops up quite a lot, e.g. in even simple cases like the typing rules for an if expression without an else branch.

If you are interested in learning a simpler statically-typed FP language and a general approach to learning these kinds of languages, here’s what I recommend: Learning functional programming in scala


#7

To be fair, else () sugar exists in other functional languages, such as OCaml.


#8

It doesn’t also trigger an upcast to Any in OCaml though.


#9

Ya, OCaml doesn’t have a top type that I remember.