Is it possible to force runtime boxing in scala dynamically? I would like a function:
def box(value :Any) :AnyRef
or
def box[T](value :T) :AnyRef
I have a generic class which may be parameterized with AnyVals but need to pass them to legacy java methods accepting collections of objects. Of course, I could implement it myself with pattern matching, but it's a bit annoying to have to do it time and time again, and it wouldn't work for user value classes.
Edit
The answer turned out as simple as surprising. Now, can I do it through reflection? Assume
class Box[T :TypeTag](private var value :T) {
def get :T = value
def set(o :Any) {
...
}
}
I would like to do a safe set, checking in the runtime if o is a subclass of T like this:
runtimeMirror(getClass.getClassLoader).classSymbol(o.getClass).toType <:< typeOf[T]
Unfortunately, typeOf[T] for Box[Long] will be a primitive, and the following check will fail on java.lang.Long, which is the runtime type of elements of Seq[Long] for example. Bottom line, when using generics with AnyVals, the compiler sometimes boxes them making runtime class checks unpredictible.
Any
toAnyRef
. (Looks like it has more to do with unboxing?) How about making it a second, separate question? – Reade