Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

object

int

scala

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: ...

like image 491
Mikaël Mayer Avatar asked May 25 '13 16:05

Mikaël Mayer


People also ask

How do you convert an integer to an object?

Converting a primitive value (an int, for example) into an object of the corresponding wrapper class (Integer) is called autoboxing. The Java compiler applies autoboxing when a primitive value is: Passed as a parameter to a method that expects an object of the corresponding wrapper class.

Can we just cast the reference to an int?

You're not casting to an int, no Object can ever be cast to an int.


1 Answers

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)
like image 130
Régis Jean-Gilles Avatar answered Sep 23 '22 00:09

Régis Jean-Gilles