17

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

3
  • 2
    Object isn't a trait - what does Int with Object even mean? Commented May 25, 2013 at 16:32
  • I'm using the Android ArrayAdapter class, and from scala it requires something of type Array[T with Object]. From Java it requires a java.lang.Object[]. Commented May 25, 2013 at 16:38
  • 1
    Can you show us your actual code so we can understand how you end up with the Array[T with Object] type? Commented May 25, 2013 at 16:41

1 Answer 1

42

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) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.