scalaimplicit-conversionscala-2.13

Implicit conversion of Int* to custom class in function call


I have a custom type MySeq extending IndexedSeq[Int] and its implicit conversion:

package example

import scala.language.implicitConversions

class MySeq(vals: IndexedSeq[Int]) extends IndexedSeq[Int] {
  def apply(i: Int): Int = vals(i)

  def length: Int = vals.length
}

object MySeq {
  implicit def seq2MySeq(vals: Int*): MySeq = new MySeq(vals.toIndexedSeq)
}

I want to be able to call some function of type MySeq => T as follows:

package example

object Hello extends App {
  def foo(xs: MySeq): MySeq = xs

  val ret = foo(1, 2, 3)
}

But I get a Too many arguments for method foo(MySeq) error when compiling with scala-2.13.8. What am I missing/misunderstanding?


Solution

  • You can implicitly convert only 1 value to another 1 value, you cannot use conversion to "overload" unary method into variadic method.

    You could implement conversions so that

    foo(Seq(1, 2, 3))
    

    would become

    foo(MySeq.seq2MySeq(Seq(1, 2, 3))
    

    but to be able to use

    foo(1, 2, 3)
    

    you would have to overload the method e.g.

    def foo(ints: Int*) = foo(MySeq(ints))