Skip to content

Instantly share code, notes, and snippets.

@Allan-Gong
Last active November 30, 2015 04:40
Show Gist options
  • Save Allan-Gong/80ae72a0e96a569f2531 to your computer and use it in GitHub Desktop.
Save Allan-Gong/80ae72a0e96a569f2531 to your computer and use it in GitHub Desktop.
Scala - difference between multiple parameter lists and a single list of parameters
// Reference: http://stackoverflow.com/questions/6803211/whats-the-difference-between-multiple-parameters-lists-and-multiple-parameters
// 1. The multiple arguments lists allow the method to be used in the place of a partially applied function:
object NonCurr {
def tabulate[A](n: Int, fun: Int => A) = IndexedSeq.tabulate(n)(fun)
}
NonCurr.tabulate[Double](10, _) // not possible
val x = IndexedSeq.tabulate[Double](10) _ // possible. x is Function1 now
x(math.exp(_))
// 2. Refer to arguments of a previous argument list for defining default argument values:
def doSomething(f: java.io.File)(modDate: Long = f.lastModified) = ???
// 3. To have multiple var args (not possible in a single argument list):
def foo(as: Int*)(bs: Int*)(cs: Int*) = as.sum * bs.sum * cs.sum
// 4. 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
// 5. 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment