Format partial functions like match functions in Scala with IntelliJ - scala

IntelliJ (14.0.3, Scala plugin 1.4) formats regular case/match blocks after a function as so (this is from some HTTP code):
get("/work") { x => x match {
case (200, result) => ...
case _ => ...
}
} // I'm not worried about this brace
If I collapse that obvious x => x match, it formats it like this:
get("/work") {
case (200, result) => ...
case _ => ...
}
That kind of formatting gets messy if the call to get("/work") uses a longer url (as I have in places). It gets even worse if I have further nested things.
Is there any way to make IntelliJ format the case statements to be indented by one tabstop relative to the original statement, instead of relative to the opening brace?

Turns out, it's a matter of setting the right code-style options.
In Settings -> Editor -> Code Style -> Scala, Wrapping and Braces -> Method call arguments, Do not align block expression parameters must be on, if Align when multiline is on.

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.

For returning Option from pattern matching, use Try?

I have lots of pattern matching code that looks as follows: If some Foo matches, a Some of Bar is returned, otherwise None, and there are lots of Foos and long constructors for Bars. Something like:
y match {
case Foo1(z) => Some(Bar1(z))
case Foo2(z) => Some(Bar2(z))
case Foo3(z) => Some(Bar3(z))
case Foo4(z) => Some(Bar4(z))
case _ => None
}
In the actual code, the constructors on the right hand side of the arrows are more complex, and there are more cases.
Now, in order to get rid of the repetitive option constructors (Some), I could do:
Try(
y match {
case Foo1(z) => Bar1(z)
case Foo2(z) => Bar2(z)
case Foo3(z) => Bar3(z)
case Foo4(z) => Bar4(z)
}
).toOption
This looks significantly cleaner to me, and from a semantic perspective it is justifiable, as the case _ is actually a situation that should not occur, thus modeling it as an exception seems justifiable. Note that it is the repetitive Somes that bug me, not the last case.
My question is whether there is some (e.g. performance) penalty to the latter approach I am not aware of.
The second version is less readable, and less correct*. There isn't much of a point in using Try if you're just going to discard the error to None. The Try is only there to catch match errors and convert them to None, but you can do that in one like with case _ => None.
There would be slightly more overhead wrapping in Try, but not enough to matter. Correctness and readability should come first.
If you really don't want to have that extra case, consider wrapping y in Option and using collect:
Option(y) collect {
case Foo1(z) => Bar1(z)
case Foo2(z) => Bar2(z)
case Foo3(z) => Bar3(z)
case Foo4(z) => Bar4(z)
}
Using collect on an Option will wrap the cases in the partial function that are defined in Some, and any cases that do not match will become None.
*By correct, I mean widely accepted use of Try.

To brace or not to brace: case statement block

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.

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.