Search code examples
scalaread-eval-print-loop

Scala if-else condition not working on REPL


I am executing this on the Scala Interpreter - REPL, I am trying to set the value of the Tuple(account_df_index, disposition_df_index) to (0,1), but on execution an error is thrown on the first line of the else block. If my understanding is correct, (0,1) should be assigned and the else block must not execute. Where am I wrong?

val extra_params = None
val extra_params_map = if (extra_params.equals(None)) {None} else{
    extra_params.toMap}

val (account_df_index, disposition_df_index) = if(extra_params.equals(None)) 
                        {
                        (0,1)
                        } else {
                        if(extra_params_map.contains("dataframe_index_map"){
                        val dataframe_map = 

                        extra_params_map.get("dataframe_index_map")
                        .get.parseJson
                        .convertTo[Map[String, Int]]
                        val account_df_index = dataframe_map.getOrElse("account", 0)
                        val disposition_df_index = dataframe_map.getOrElse("disposition", 1)
                        (account_df_index, disposition_df_index)
                        } else{
                              (0,1)
                              }
                        }   

Solution

  • There are a number of things wrong with this code. I'll focus on two things.

    variable initialization via pattern matching

    val (a, b, c, d) = if (someCondition) doThis()
                       else               doThat()
    

    In this example 4 different variables, a, b, c, and d, are created and initialized. The compiler recognizes that they grouped in a 4-tuple and makes the pattern match if the right side of the equals = returns a 4-tuple. So this only works if both doThis() and doThat() return the same thing, i.e. a 4-tuple with the same type pattern.

    None is part of Option

    If a variable might be None then that variable's type is Option[X] where X is the type of the variable if it is not None.

    val extra_params_map: Option[Map[Int,Int]] = if (extra_params.isEmpty) None 
                                                 else Some(extra_params.toMap)
    

    Notice that Some() is the compliment of None and the result type is Option. In this case it is Option[Map[Int,Int]] assuming that extra_params.toMap returns a Map[Int,Int].