scalasplat

Scala Splat inner workings


I know in scala I can say

def foo(x: Int*) ...

foo(Seq(1,2,3): _*)

But I can't say

foo(Seq(1,2,3))

So there must be some implicit conversion going on. What is this implicit conversion? What is the actual method that makes this happen. Or, if I'm wrong, how does it actually work?


Solution

  • There is no implicit conversion when you use Seq with the type annotation _*, because a repeated parameter is basically a Seq already.

    However, if you used an Array, then there would be an implicit conversion, and

    foo(Array(1,2,3): _*)
    

    would be

    foo(wrapIntArray(Array(1,2,3)):_*)
    

    wrapIntArray is an implicit function defined in Predef.

    implicit def wrapIntArray(xs: Array[Int]): ArraySeq.ofInt
    

    As to why the latter one (without the type annotation) is not accepted, I'm guessing it's just a design choice not to puzzle the developer on how it worked :).