Search code examples
scalatypesruntime-typetreehugger

Get Scala type name for common AnyVal types/primitives


In my scala code I have a Class[_ <: AnyVal] instance, such as the one obtained from classOf[Int].

When I try to obtain the scala type name from this (using classOf[Int].getName), I am expecting to see "scala.Int", but instead I am getting the primitive Java type's name: "int"

How can I get the scala type name from my Class variable, in case I am dealing with either a java primitive equivalent, or the default boxed java equivalent (such as java.lang.Integer)


In case you are wondering why I would need this; I am generating some scala code using treehugger, and the information about whether I need to generate e.g. a scala.Int comes from a library that provides a Class[_]


Solution

  • If you only want to handle primitive types,

    def scalaName(cls: Class[_]) = 
      if (cls.isPrimitive) s"scala.${cls.getName.capitalize}" else cls.getName
    

    Unfortunately the Java standard library doesn't (still, as far as I know) provide a way to convert between boxed and primitive Classes, so the best way is to handle them all individually:

    val classesMap = Map[Class[_], Class[_]](
      classOf[java.lang.Integer] -> classOf[Int], 
      classOf[java.lang.Short] -> classOf[Short], 
      ...
    )
    
    def scalaName1(cls: Class[_]) = scalaName(classesMap.getOrElse(cls, cls))
    

    You may also want to handle Void.TYPE specifically (e.g. converting to scala.Unit).