Stanley Stanley - 1 month ago 13
Scala Question

Scala Seq - How to solve overloaded method value with alternatives due to Seq

I have a function as follows:

def foo(sequence: Seq): Unit = {
...
bar.select(sequence);
}


I obtained an error,
overloaded method value select with alternatives
. I'm new to Scala's syntax, and I don't know the exact term, so I have been searching online without any results.

In particular, Scala appears to be confused as to which of the
select
method I am calling. From the documentation, there are 2
select
methods (Source: https://spark.apache.org/docs/1.5.2/api/scala/index.html#org.apache.spark.sql.DataFrame)

I have tried the following, but perhaps because I am not familiar with the syntax, I was not able to succeed:

bar.select(sequence.asInstanceOf[Seq[Column]]);


How do I tell Scala that I want it to use
select(cols: Column*)
instead of alternatives? And if it is fine, could the answer include what concept this is - just so I can tag it properly, and learn something new.

Answer

Declare your foo method like this and use _*. As shown below

def foo(sequence: Seq[Column]): Unit = {
    bar.select(sequence: _*)
}

Explanation select takes var args. When you want to pass Seq to a method which takes var args you have to explicitly say _* So that compiler can accept the Seq as var args.

Scala REPL example

scala> def foo(a: Int*) = 1
foo: (a: Int*)Int

scala> foo(Seq(1, 2))
<console>:13: error: type mismatch;
 found   : Seq[Int]
 required: Int
       foo(Seq(1, 2))
              ^

scala> foo(Seq(1, 2): _*)
res1: Int = 1

notice calling foo(Seq(1, 2) gives a compilation error this error can be fixed if we guide the compiler by giving type explicitly as _*