Skip to content

Instantly share code, notes, and snippets.

@Allan-Gong
Created May 3, 2016 14:21
Show Gist options
  • Save Allan-Gong/3ef3eaf38f564ce60711a78232eab9e9 to your computer and use it in GitHub Desktop.
Save Allan-Gong/3ef3eaf38f564ce60711a78232eab9e9 to your computer and use it in GitHub Desktop.
Tricks in scala language
// when passing parameters to method calls. You may replace parenthesis with curly braces if, and only if,
// the method expects a single parameter. For example:
List(1, 2, 3).reduceLeft{_ + _} // valid, single Function2[Int,Int] parameter
List{1, 2, 3}.reduceLeft(_ + _) // invalid, A* vararg parameter
// Why multiple parameters lists scala ?
// First: you can have multiple var args:
def foo(as: Int*)(bs: Int*)(cs: Int*) = as.sum * bs.sum * cs.sum
// ...which would not be possible in a single argument list.
// Second, it aids the type inference:
def foo[T](a: T, b: T)(op: (T,T) => T) = op(a, b)
foo(1, 2){_ + _} // compiler can infer the type of the op function
def foo2[T](a: T, b: T, op: (T,T) => T) = op(a, b)
foo2(1, 2, _ + _) // compiler too stupid, unfortunately
// And last, this is the only way you can have implicit and non implicit args, as implicit is a modifier for a whole argument list:
def gaga [A](x: A)(implicit mf: Manifest[A]) = ??? // ok
def gaga2[A](x: A, implicit mf: Manifest[A]) = ??? // not possible
// What is thunk in scala ?
// This is called either a nullary function or a thunk, and is an example of call-by-name evaluation
// You can use nullaries pretty much anywhere you have a parameter list.
// They are basically just syntactic sugar around zero-argument functions that make them look like ordinary values,
// and are invoked whenever they are referenced.
def doSomething(op: => Unit) {
op
}
doSomething {
println("Hello!")
}
// is exactly the same as:
def doSomething(op: () => Unit) {
op()
}
doSomething(() => println("Hello!"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment