Skip to content

Instantly share code, notes, and snippets.

@jaimefjorge
Created July 20, 2011 07:46
Show Gist options
  • Save jaimefjorge/1094536 to your computer and use it in GitHub Desktop.
Save jaimefjorge/1094536 to your computer and use it in GitHub Desktop.
Scala Coding Method Chaining style
/**
* This is from community accepted conventions and feel free to judge upon them.
*
* Upon Method Invocation chaining, one can prefer the 'fooIndent' method over 'fooNotIndent'
* (as well as barIndent over barNotIndent),
* Not only it improves readibility upon reading (by gradually grasping the functionality) but also it does not consume
* the whole screen (thus not making you scroll).
*
* The use of '.' upon invocation is debatable.
* Some argue that the leading '.' should be removed [2]
* while others think that it gives some clarity and "profilatic safety" [1][3]
*
*
* [1] http://stackoverflow.com/questions/6471949/what-is-the-accepted-recommended-syntax-for-scala-code-with-lots-of-method-chaini
* [2] http://davetron5000.github.com/scala-style/
* [3] http://stackoverflow.com/questions/4238902/refactoring-layout-of-functional-scala
*
* Note: this is not compilable. It is only for the purpose of style viewing
*/
object Test{
def fooNotIndent : List[Int] = (1 to 100).view.map { _ + 3 }.filter { _ > 10 }.flatMap { table.get }.take(3).toList
def fooIndent: List[Int] =
(1 to 100)
.view
.map { _ + 3 }
.filter { _ > 10 }
.flatMap { table.get }
.take(3)
.toList
/**
* Another example
*
* Note: barNotIndent and Indent were extracted from [3]
* while barIndent was not the chosen answer, it isolates the aspect I'm demonstrating
*/
def barNotIndent = Console.println(io.Source.fromFile("names.txt").getLines.mkString.split(",").map{x:String => x.slice(1, x.length -1)}.sortBy { x => x}.zipWithIndex.map{t =>{ (t._2 +1)*(t._1.map{_.toChar - "A"(0).toChar + 1}.sum)}}.sum);
def barIndent = Console.println(
io.Source.fromFile("names.txt")
.getLines.mkString.split(",")
.map{x:String => x.slice(1, x.length -1)}
.sortBy { x => x}
.zipWithIndex
.map{t =>{ (t._2 +1)*(t._1.map{_.toChar - "A"(0).toChar + 1}.sum)}}
.sum);
}
@leopard627
Copy link

Cool

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment