简体   繁体   English

在Scala中传递varargs时,如何避免隐式类型转换?

[英]How to avoid implicit type conversion when pass varargs in Scala?

I wrote a function like this: 我写了这样的函数:

def a (params:Any*) = {
    val clazzes = params.map(_.getClass)
    ...
}

But when I pass in a param with type of Scala Long, it is automatically converted to java.lang.Long Is there any way to avoid that? 但是,当我传入Scala Long类型的参数时,它会自动转换为java.lang.Long有什么方法可以避免这种情况?

You can suppress the default implicit conversion that is defined in the Predef: 您可以禁止在Predef中定义的默认隐式转换:

import Predef.{long2Long=>_,println}

object Test{

  val tL : java.lang.Long = 1L

}

You'll then get a type error : 然后,您将得到一个类型错误:

Error:(26, 29) type mismatch;
 found   : scala.Long(1L)
 required: java.lang.Long
  val tL : java.lang.Long = 1L
                        ^

But, in your case your parameters are getting boxed as an Any* (a wrapped array). 但是,在您的情况下,您的参数将被装箱为Any *(包装的数组)。 The runtime boxed representation of a scala long is java.lang.Long. scala long的运行时框式表示形式是java.lang.Long。 This isn't an implicit conversion, so it isn't going to be suppressed. 这不是隐式转换,因此不会被抑制。

import Predef.{long2Long=>_,println}

object Test extends App{

   def a(params: Any*) = {
    for(p<-params) yield(p.getClass)
  }

  println(a(1L))

}

Output: 输出:

ArrayBuffer(class java.lang.Long)

Its possible you want to write generic code that avoids boxing. 您可能希望编写避免装箱的通用代码。 If thats the case you'll need to look into specialization. 如果是这样,您需要研究专业化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM