To brace or not to brace: case statement block - scala

I am asking a specific question here (not an opinion): is there any scala style guide recommendation for the following "case o:" addressing whether the (optional) use of braces were to be avoided or if either with/without were both acceptable:
def mycase(x : Int) = {
x match {
case 0 =>
println("zero")
println("blah zero")
case 1 =>
println("one")
}
I was not initially convinced it would even work (thought it might do a fall through): but it does the correct breakout:
scala> mycase(0)
zero
blah zero
I specifically want to know if there were a canonical answer on this (not "I prefer" , etc.). E.g. for java, Sun had stated long ago that placing the initial curly brace for a method may happen either on same or next line - both are acceptable. is there such a clear answer in this case?
UPDATE An answer provided below by #acjay provides a link to the style guide. Inside here is a specific blurb.
from http://docs.scala-lang.org/style/control-structures.html#curlybraces
case - Omit braces if the case expression fits on a single line.
Otherwise, use curly braces for clarity (even though they are not
required by the parser).

The Scala's style guide about this http://docs.scala-lang.org/style/control-structures.html#curly-braces seems changed, where it says
case - Always omit braces in case clauses.
Actually, when editing in IntelliJ, it will remind user of unnecessary braces around case block.
Thus, to avoid introducing further confusion to users, please make a correction to the accepted answer :)

The Scala Documentation Style Guide says:
case - Omit braces if the case expression fits on a single line.
Otherwise, use curly braces for clarity (even though they are not
required by the parser).
Therefore, the correct format is:
def mycase(x : Int) = x match {
case 0 => {
println("zero")
println("blah zero")
}
case 1 => println("one")
}
Separate from the question, but with pertinence to the example given, the declarations section of the style guide mentions the preferred formatting for the match as such:
Methods which contain a single match expression should be declared in the following way:
def sum(ls: List[Int]): Int = ls match {
case hd :: tail => hd + sum(tail)
case Nil => 0
}

In regards to the same/next line for the curly brace the Style Guide is explicit on that as well:
Opening curly braces ({) must be on the same line as the declaration
they represent:
def foo = {
...
}
Technically, Scala’s parser does support GNU-style notation with
opening braces on the line following the declaration. However, the
parser is not terribly predictable when dealing with this style due to
the way in which semi-colon inference is implemented. Many headaches
will be saved by simply following the curly brace convention
demonstrated above.

Related

Curly braces in Scala method call [duplicate]

This question already has answers here:
Why use curly braces over parentheses?
(3 answers)
Closed 4 years ago.
In Scala, we can have:
println { "Hello, world!" }
And from the book 'Programming in Scala':
The purpose of this ability to substitute curly braces for parentheses for
passing in one argument is to enable client programmers to write function
literals between curly braces. This can make a method call feel more like a
control abstraction.
What does this statement mean?
This is syntactic sugar just for look and feel. When a function takes a function as argument like in
def doWith[A, B](todo: A => B): B = ???
You would normally have to call it like
doWith( input => ... )
// or even
doWith({ input => ... })
In scala it is allowed to replace parenthesis with with curlies, so
doWith { input =>
...
}
Has the look and feel of a control structure like
if (...) {
...
}
Imho, that makes calling higher order functions like 'map' or 'collect' much more readable:
someCollection.map { elem =>
...
...
}
which is essentially the same as
someCollection.map({ elem =>
...
...
})
with less chars.
"Control abstractions" are e.g. if, while, etc. So you can write a function
def myIf[A](cond: Boolean)(ifTrue: => A)(ifFalse: => A): A =
if (cond) ifTrue else ifFalse
(if you aren't familiar with : => Type syntax, search for "by-name parameters") you can call it as
val absX = myIf(x < 0) { -x } { x }
and it looks very similar to normal if calls. Of course, this is much more useful when the function you write is more different from the existing control structures.
In addition to (regular) functions and by-name arguments, braces also help with partial functions:
processList(l) {
case Nil => ...
case h :: t => ...
}
and sequences of expressions:
doSomething {
thing1;
thing2
}
Note that (thing1; thing2) is not a valid expression in Scala like it would be in, say, ML.
Actually what I have noticed the difference between the curly braces{} and parenthesis() is that you can write multiple lines in the curly braces. While in parenthesis() you can’t write more then one line for example.
val x :[List[Int]]=List(1,2,3,4,5,6,7,8)
x.map(y=> y*5) //it will work fine
x.map(y=>
case temp:Int=>println(temp)
case _ => println(“NOT Int”)) //it will not work
x.map{y=>
case temp:Int=>println(temp)
case _ => println(“NOT Int”)} //it willwork
So we can say it’s just the synthetic sugar to allow developer to write more then none line without ; that’s it it may have some other reason too.

Is throwing exceptions in Scala considered a side-effect?

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!" :)
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.
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.

How to account for all cases of an enum on the right-hand side of a pattern match

Exhaustive pattern matching is great, but it only appears to work on the left-hand side of the case (=>) operator.
I am curious if there is a way that a person can verify that the output of a function (or expression) can be bound to that enumeration. The goal would be to have the compiler tell me when I forget to output an item from the enumeration.
In my example, I make use of the following enumeration containing three items:
object MyEnum {
sealed trait t
case object E1 extends t
case object E2 extends t
case object E3 extends t
}
And here is a pattern-match expression that would produce a compile-time warning (as we already know):
def foo( e : MyEnum.t ) : Boolean =
e match {
case MyEnum.E1 => true
case MyEnum.E2 => false
case MyEnum.E3 => true // if we leave this line out, we get a warning
}
Scala would complain if we left MyEnum.E3 out of the pattern matching expression, citing a non-exhaustive pattern match. This is profoundly beneficial, but I wonder if the reverse is possible.
Can we account for all cases of MyEnum.t on the right-hand side of =>?
Here is an example that highlights this:
def bar( s : String ) : Option[MyEnum.t] =
s match {
case "a" => Some(MyEnum.E1)
case "b" => Some(MyEnum.E2)
case "c" => Some(MyEnum.E3) // if we leave this out, no warning
case _ => None
}
In this example, if we leave out the line with MyEnum.E3, then the compiler just carries on as if nothing is wrong. The assertion I would like to make, is:
forall MyEnum.t (aliased as e) there exists Some(e) | None
I understand that this could be easily covered by a run-time test, but I'm curious if there is a way to check this statically.
Thanks.
I am going to push my luck and claim it is not possible (let's keep this a secret from Odersky). If the Scala compiler was able to detect such situations, I think it would be even slower than it already is ;)
The only way I could see is to define foo similarly to how you have done, and define bar by making it iterate over foo to make a reverse map, but that doesn't make much sense to me, and might not work in your specific case.
I think your case is a very good example for when unit tests are useful, so why not just write one?
No, it is not possible, because this is equivalent to the Halting Problem, which was proven unsolvable in 1936.

Dont understand how a multi-line statement can be parsed without {} curly blocks

I follow the C family (PHP is a wannabe!) requirement that a statement that spans over multiple lines must be enclosed in curlies.
Scala avoids parse errors in this code from O'Reilly's Programming Scala.
def apply(specification: String): Option[Widget] = specification match {
case ButtonExtractorRE(label) => new Some(new Button(label))
case TextFieldExtractorRE(text) => new Some(new TextField(text))
case _ => None
}
whereas I believe it should look like (the body of the function is enclosed):
def apply(specification: String): Option[Widget] = {
specification match {
case ButtonExtractorRE(label) => new Some(new Button(label))
case TextFieldExtractorRE(text) => new Some(new TextField(text))
case _ => None
}
}
while Scala can parse it, can a programmer "get it"? I dont. Am I missing some intuitive idea?
Should I rather avoid such a practice, if it leads to practical problems (like poor readability?
In Scala much more things (including if, match and for with yield) return a result as in other languages. And more data structures are immutable, which often leads to transformation chains of map, filter, flatMap, collect etc - which also gives just one result. Last but not least Scala has excellent support for tuples, which means that you often get back a tuple as a single result where other languages have to sort out single values.
So in general Scala doesn't deal as much with variables storing intermediate values as other languages do. That means a function is often just an equation f(a) = b, where b might be quite complex, but is still one chain returning a single result. So it is just naturally to adopt that syntax, which makes immediately clear that you are not juggling with intermediate results, but that you follow a more functional style.
It should be mentioned that functional languages (except the "lispy" family with a quite different syntax) have similar conventions. So if you look at Haskell, F# or Erlang, you usually won't see any "blocks" for methods. There are structures like let, case and (for Haskell) do which might look a little bit like blocks, but are expressions as well.
When you say a function = (without the curly braces), it compiles and works fine because it's a single expression. Your 'match' expression always evaluates to one single value. And the 'match' is the only thing in your function. So, really it's only a single expression, even if it spans a few lines. If your apply function requires multiple expressions and statements, then yes, you do need curly braces.
I follow the C family requirement that a statement that spans over multiple lines must be enclosed in curlies.
Wrong.
#include <iostream>
using namespace std;
int main() {
bool b = true;
char c = 'a';
if (b) switch (c) {
case 'a': cout << "It's a" << endl; break;
default : cout << "Not a" << endl; break;
}
}
Here the true branch of the if statement spans multiple lines, but is not enclosed in braces. In fact, have you ever used if/else if?
if (foo) {
// do foo stuff
else if (bar) {
// do bar stuff
} else {
// do non-foo/bar stuff
}
Syntactically, there is no special treatment for else if. else is just a regular key word. This is syntactically equivalent to
if (foo) {
// do foo stuff
else {
if (bar) {
// do bar stuff
} else {
// do non-foo/bar stuff
}
}
Note that brackets are not required to surround the inner if. This is because an if/else statement is a self-contained single expression. The rule is not to put braces around any statement that spans multiple lines. Rather, I think it fair to say that any statements separated by semicolons must be grouped with braces. Disclaimer: I am not a C expert. Check the docs if you need to be sure.
Nor am I a Scala expert, but generally I think the Scala mindset is to remove braces whenever possible, subject to good judgement and taste, of course.
You have a function that consists only of a single expression. Many languages still require to enclose it in curly braces.
This might be confusing if you are only used to such languages. But after using Scala a little a function definition with a single expression as body starts to look like a function valued 'variable'.
From that point you'll stop missing the curly braces.
So: in almost all cases I'd skip all the braces I don't need. I had not a problem with it in a long time.

Need clarification on Scala literal identifiers (backticks)

Reading the Programming in Scala 2nd Ed and I came across this:
literal identifier
"The idea is that you can put any string that's accepted by the runtime as an identifier between backtick"
I'm not entirely sure why I would use this? The book gave a use case of accessing the static yield method in Java's Thread class.
So since in Scala, yield is a reserve word, if I use yield with backticks,
Thread.`yield`()
it would ignore the Scala's yield and let me access the Java's Thread class's method yield instead?
Thank you in advance.
Exactly. Using backticks, you can more or less give any name to a field identifier. In fact, you can even say
val ` ` = 0
which defines a variable with name (one character of whitespace).
The literal definition of identifiers is useful in two cases. The first case is, when there is already a reserved word of the same name in Scala and you need to use a Java library which does not care about that (and of course, why should it).
The other use case comes with case statements. The convention is that lower case names refer to match variables, whereas upper case names refer to identifiers from the outer scope. So,
val A = "a"
val b = "b"
"a" match {
case b => println("b")
case A => println("A")
}
prints "b" (if the compiler were dumb enough not to fail with saying case A were unreachable). If you want to refer to the originally defined val b, you need to use backticks as a marker.
"a" match {
case `b` => println("b")
case A => println("A")
}
Which prints "A".
Add There is a more advanced use case in this recent question method with angle brackets (<>) where the backticks were needed to get the compiler to digesting the code for a setter method (which in itself uses some ‘magic’ syntax).
Thank you #Debilski, it helps me to understand this code below from AKKA doc :
class WatchActor extends Actor {
val child = context.actorOf(Props.empty, "child")
...
def receive = {
...
case Terminated(`child`) ⇒ ...
}
}
The case :
case Terminated(`child`)
matches a message of type Terminated with ActorRef field equals to child which is defined earlier.
With this statement :
case Terminated(c)
We match every Terminated messages with any reference of ActorRef mapped in c.