Home > database >  Illegal start of simple expression when when defining new value in if-statement
Illegal start of simple expression when when defining new value in if-statement

Time:12-11

I'm trying to declare a new value in an if-statement, but get the Illegal start error with the following code.

// df(: DataFrame) is defined earlier
if (df.columns.contains(f"original_cols_$prev_k%s"))
  val df_fixed = df.drop(f"original_cols_$prev_k%s").drop(f"scaled_cols_$prev_k%s")
else // No change, but to respect the immutability...
  val df_fixed = df

If I wrap it in the wave brackets ...

if (df.columns.contains(f"original_cols_$prev_k%s")){
  val df_fixed = df.drop(f"original_cols_$prev_k%s").drop(f"scaled_cols_$prev_k%s")
} else { // No change, but to respect the immutability...
  val df_fixed = df
}

... I don't get errors in these rows but later on get the "not found: value df_fixed"-error. What am I doing wrong?

CodePudding user response:

Scala expressions are composed of operators and operands. A conditional expression (if-else) expects other expressions after if and else. In the first case, you are using a definition (eg: val int = 10), when an expression is expected. This was the cause of the first error.

But by putting the definition inside curly braces you made it a block expression, so the compiler doesn't complain anymore.

if(true) {
  val integer = 10
}

However, integer has a local scope and is not available outside. Thus the second error of not found.

What you need is:

val integer = 
  if(somecheck()) 
    10 
  else 
    20 
  • Related