Reputation: 1803
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?
Upvotes: 0
Views: 82
Reputation: 14825
This {}
is used for multiline code block and are optional for one line code. Anonymous function in Scala looks like this val square = { x: Int => x * x }
def foo (b : Boolean, input : Any): Unit = {
val changedInput = if (b) input else bar(input)
dowork (changedInput)
}
Upvotes: 0
Reputation: 12848
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.
Upvotes: 4
Reputation: 30746
def foo(b: Boolean, input: Any): Unit =
dowork(if (b) input else bar(input))
Upvotes: 0