Saar Saar - 2 months ago 5
Scala Question

Scala newbie - if-else

A scala method gets an input and should operate either on the input directly or a calculation of it, for instance consider the following code:

def foo (b : Boolean, input : Any): Unit ={
val changedInput = {if (b) input else bar(input) }
dowork (changedInput)
}


Is it appropriate to use an anonymous function like in the example above or there another syntax?

Answer

There is no anonymous function in your example. And the code you write, IMO, is just fine.

I guess you regard {if (b) input else bar(input) } as anonymous function. It is called "block" in scala, which is just a expression whose value is the last expression contained in the block. For instance,

The value of { expr1; expr2; expr3} is the value of expr3. So your code can just be written as

def foo (b : Boolean, input : Any): Unit ={
  val changedInput = if (b) input else bar(input)
  dowork (changedInput)
}

since there is only one expression in your block.

Comments