本文介绍了VarArgs的隐式def的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是注意到implicit def在var args中似乎不起作用.

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

例如,我有一个使用java.lang.Byte...作为其参数输入的java函数.函数调用由采用scala.Byte的scala方法包围.

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*) = {

  }

出于某种原因,我必须明确输入 convertTest() 才能使其正常工作.

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

因此,我尝试了一些没有varargs参数的操作,并发现确实如此,它确实可行:

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?

推荐答案

带有varargs参数的隐式转换没有多大意义,因为您使用varargs参数,因此在调用时无需显式创建集合.该函数,但具有隐式转换函数,该函数会自动为您调用.

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.

您可以定义从Seq[Byte]Seq[java.lang.Byte]的隐式转换(如在您的第二个示例中一样),并且仍然在testtest2中使用varargs表示法(如您的第一个示例中).

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

可以用作:

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

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

这篇关于VarArgs的隐式def的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 12:35