Error with varargs for function-objects in Scala?

前端 未结 2 653
无人及你
无人及你 2020-12-01 20:45

Why does this not work?

val f = (args: Int*) => args.sum

error: \')\' expected but identifier found.
val f = (args: Int*) => args.sum
                         


        
2条回答
  •  無奈伤痛
    2020-12-01 21:32

    There's also a good explanation on this given by Lex Spoon here here

    The syntax is a little misleading here; perhaps it is being too cute. The Any* syntax for varargs makes it look like Any* is itself a type. Really, the * is an annotation on the method parameter, not on the type.

    When you write down a function type using the T1=>T2 syntax, both T1 and T2 need to be plain old bona fide types. Scala provides oodles of kinds of types, but vararg types are not one of them.

    In practical code, the way out is to explicitly use a sequence type. In fact, if you look at the inferred type for good2, you will see it involves Seq[Any] rather than Any*.

提交回复
热议问题