Reputation: 59
Having the code below:
val prices = cars map (car => {
val price = car.getPrice
Logger.info(s"Car price is $price")
price
})
Is using parentheses fine in the above case or there is a strict imperial to use curly braces like below:
val prices = cars map { car => {
val price = car.getPrice
Logger.info(s"Car price is $price")
price
}}
I do not like two curly braces and prefer ({ ... })
style, but was warned by another developer that the inside function is side-effecting (logging message) and is 3 lines of code so it must be used with two curly braces and that the whole Scala community uses double curly braces in these cases.
I googled scala code and found this one:
def failed: Future[Throwable] =
transform({
case Failure(t) => Success(t)
case Success(v) => Failure(new NoSuchElementException("Future.failed not completed with a throwable."))
})(internalExecutor)
It has multiple lines but no side effects and my nice notation ({...})
is used here. Should it be changed when the code contains side-effects? Personally I do not like that even if the whole community says "Yes, use double curly braces!" :)
Upvotes: 1
Views: 257
Reputation: 13922
In your particular case I would actually only use curly braces and no parens:
val prices = cars map { car =>
val price = car.getPrice
Logger.info(s"Car price is $price")
price
}
The example you posted from the scala code is only using parentheses out of necessity, since transform
is actually a function with multiple argument lists (i.e. transform(args1)(arg2)
).
I have not heard of any convention relating side-effecting code to a particular choice of block delimiter (()
vs {}
), but I do find I prefer the look of {}
when there are multiple lines in that block.
Upvotes: 1
Reputation: 12565
I have never heard about that you should curly braces when there is a side effect in a block of code. Use () for a single statement, and {} for multiple statements. What you call nice notation ({...})
is perfectly fine.
Upvotes: 0