Scala:如何强制将整数包装为对象? [英] Scala: How to force wrapping an integer as an object?
问题描述
我在这里收到错误:
val a: Int = 1
val i: Int with Object = a
如何将此1转换为scala中的整数对象?
我的目的是将它传递给数组[带对象的Int]
。
目前显示错误:
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
^
编辑
我有这个错误,因为我使用的是android ArrayAdapter
,以及因此,通过定义:
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) { ... }
它会抛出这个错误:
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])
所以我需要用替换
T
类中的T<:Object
类ImageAdapter [T< ;: Object](ctx:...
So I need to replace T
with T <: Object
in class ImageAdapter[T <: Object](ctx: ...
推荐答案
Int
是一种scala类型,通常映射到java的 int
,但是在装箱时会映射到 java.lang.Integer
。无论是否装箱,scala都是透明的。
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.
在任何情况下, Int
绝对不是 java.lang.Object
的子类型。实际上 Int
是 AnyVal
的子类型,它不是的子类型java.lang.Object
。因此,带对象
的Int是非常荒谬的,因为你不能拥有任何一个<$ c的具体类型$ c> Int 和一个 java.lang.Object
。
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
或者更多的是:
val i: AnyRef = a
当然,这些都没有编译,但你可以强制装箱 Int
值转换为 AnyRef
:
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]
与一般情况不同,施放 AnyVal
到 AnyRef
总是安全的,并会强制装箱。
Unlike in the general case, casting an AnyVal
to an AnyRef
is always safe, and will force the boxing.
您还可以使用更具体的 Int.box
函数:
You can also use the more specific Int.box
function:
val i: AnyRef = Int.box(a)
这篇关于Scala:如何强制将整数包装为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!