Mikaël Mayer
Mikaël Mayer

Reputation: 10711

Scala: How to force wrapping an integer as an object?

I am getting an error here:

val a: Int = 1
val i: Int with Object = a

How can I convert this 1 to an integer object in scala? My purpose is to pass it to an Array[Int with Object]. It currently displays the error:

error type mismatch
found : Int(1)
required: Int with java.lang.Object
       val i: Int with Object = a
                                ^

EDIT

I have this error because I am using an android ArrayAdapter from scala, and therefore by defining:

class ImageAdapter[T](ctx: Context, viewResourceId: Int, pointers: Array[T]) extends ArrayAdapter[T](ctx, viewResourceId, pointers) { ... }

it throws me this error:

overloaded method constructor ArrayAdapter with alternatives: 
(android.content.Context,Int,java.util.List[T])android.widget.ArrayAdapter[T] <and> 
(android.content.Context,Int,Array[T with Object])android.widget.ArrayAdapter[T] <and> 
(android.content.Context,Int,Int)android.widget.ArrayAdapter[T]
   cannot be applied to (android.content.Context,  Int, Array[T])

So I need to replace T with T <: Object in class ImageAdapter[T <: Object](ctx: ...

Upvotes: 16

Views: 12641

Answers (1)

R&#233;gis Jean-Gilles
R&#233;gis Jean-Gilles

Reputation: 32719

Int is a scala type which usually maps to java's int, but will map to java.lang.Integer when boxed. Whether it's boxed or not is mostly transparent in scala.

In any case, Int is definitely not a sub-type of java.lang.Object. In fact Int is a sub-type of AnyVal which is not a sub-type of java.lang.Object. Thus Int with Object is pretty much nonsensical, given that you cannot have any concrete type that is both an Int and a java.lang.Object.

I think what you meant is rather something like:

val i: Object = a

Or more idomatically:

val i: AnyRef = a

Of course, none of this compiles, but you can force the boxing of the Int value by casting to AnyRef:

val i: AnyRef = a.asInstanceOf[AnyRef]

Unlike in the general case, casting an AnyVal to an AnyRef is always safe, and will force the boxing.

You can also use the more specific Int.box function:

val i: AnyRef = Int.box(a)

Upvotes: 41

Related Questions