scala - VarArgs A* vs Seq[A] parameters to function -
i'm using scala 2.11 . if create function :
def func1 (a: int* ) : int = a.reduce(_+_)
i call using
func1(1,2,3,4) // 10 func1(seq(1,2,3,4) : _*) //10
which fine.
but when try define function literal :
val func2:(int*) => int = _.reduce(_+_)
i error saying :
<console>:5: error: type mismatch; found : int* => int required: seq[int] => int lazy val $result = instance.`func2`
why want seq[int]
in second case not in first though definition same?
how varargs being passed in first case such reduce able invoked on them?
scala makes distinction between methods , functions. func1
method parameter repeated, , desugared under hood simple seq
. on other hand, your func2
function, , repeated parameters not allowed in context.
if compiler expects function given method instead, performs eta-expansion. example, method def(s: string) = s
turned function (s: string) => s
. i'm saying make point distinction between methods , functions clear , important.
note link provided says "function declarations , definitions", kind of clumsy naming, since it's talking methods, not functions. function value other , can e.g. kept in collection or returned function. methods can't.
one final comment , i'm done: don't make common mistake , think "def method, val function". function can defined using def
instead of val
, in case it's still function value, it's evaluated @ point of usage instead of point of declaration. best way differentiate methods functions check parameters: def foo(someparameter: x): y
method. functions cannot have "(someparameter: x)" part. instead, function value, , type x => y:
// method def foo(x: x): y = // code returns y // function def foo: x => y = (x: x) => // code returns y
i deliberately used def
function make point (to prevent readers making val-def mistake), it's more common define functions using val
.
wiki
Comments
Post a Comment