Implicit def with VarArgs

ぃ、小莉子 提交于 2019-12-02 11:19:36

问题


I just noticed that implicit def doesn't seem to work in var args.

For example, I have a java function that takes java.lang.Byte... as its parameter input. The function call is surround by a scala method that takes scala.Byte.

  implicit def convertTest(bytes: Byte*): Seq[java.lang.Byte] = bytes.map(b => b : java.lang.Byte)

  def test(data: Byte*): Unit ={
    test2(convertTest(data: _*): _*)
  }

  def test2(data: java.lang.Byte*) = {

  }

For some reason I have to explicitly type convertTest() for this to work.

So I tried something without the varargs parameter and found that indeed if I do this, it works:

  implicit def convertTest(bytes: List[Byte]): java.util.List[java.lang.Byte] = bytes.map(b => b : java.lang.Byte).asJava

  def test(data: List[Byte]): Unit ={
    test2(data)
  }

  def test2(data: java.util.List[java.lang.Byte]) = {

  }

Can someone please explain this to me?


回答1:


An implicit conversion with a varargs parameter does not make much sense, since you use a varargs parameter so you don't need to explicitly create a collection when you call the function, but with a implicit conversion function, the function is called for you automatically.

You can define a implicit conversion from a Seq[Byte] to a Seq[java.lang.Byte] (like in your second example) and still use the varargs notation in test and test2 (like in your first example).

implicit def convert(bytes: Seq[Byte]): Seq[java.lang.Byte] =
  bytes.map(b => b : java.lang.Byte)

def test(data: Byte*) = test2(data: _*)
def test2(data: java.lang.Byte*) = data.length

Which can be used as :

scala> test(1.toByte, 2.toByte)
res2: Int = 2

scala> test(1.toByte, 2.toByte, 3.toByte)
res3: Int = 3


来源:https://stackoverflow.com/questions/32301449/implicit-def-with-varargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!