简体   繁体   中英

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?

You can suppress the default implicit conversion that is defined in the 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). The runtime boxed representation of a scala long is 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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