0

I would like to implement something, probably a macro, to implement something like

Int --> java.lang.Integer
Float --> java.lang.Float

so that I can implement something like

def box[X <: AnyVal : Numeric](x: X) : Boxed[X] = ...

that would cause Boxed[Int] to become java.lang.Integer, when instantiated. I am not too concerned with the specific syntax or method of implementation so long as I can write generic methods and classes that can perform ad hoc mappings on types like above. I know that the Scala library already has implicits like int2Integer for boxing and unboxing, but I need to explicitly map types in a way that the compiler can typecheck. This is mainly for implementing a typeclass whose instances have a type member that depends on the type parameters but in a non parametric way. Currently I am defining this type member explicitly in each instance of the typeclass, instead of computing it from the type parameters, but that adds boilerplate to all the instances

EDIT

The above function is just an illustration. Really I am writing type class where I need to say something like:

trait Mapping[T, U] {
   type MapBase = java.util.Map[Box[T], Box[U]]
   type MapType <: MapBase
   def create : MapType
   ...
}

Where Box[T] behaves as described above. This is intended to interface with specialized Java collection libraries like FastUtil & Trove. Instances of the type class would instantiate MapType to specialized classes, so that

implicit object LongIntMapping extends Mapping[Long, Int] { type MapType = Int2LongOpenHashMap def create : MapType = ... }

should automatically get MapBase = Map[java.lang.Long, Java.lang.Integer] since that is what the interface that FastUtil Int2LongOpenHashMap implements even though it stores unboxed primitives. This is the general pattern in FastUtil: collections of native types implement Java collection interfaces for the corresponding boxed types and that is the concept I am trying to implement systematically. This of course still requires a typeclass instance for each FastUtil collection I want to use. I am also looking into macros to solve/reduce this problem. Mybe macros even avoid the need for typeclasses, but is for production code and macros being experimental ...

4

0 回答 0