Last active
November 30, 2015 04:40
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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