get和在Kotlin中的区别是什么?

我正在使用Kotlin语言+ LibGDX库进行游戏。

Kotlin版本: 1.1.2-4

LibGDX版本: 1.9.6

正式文件说

 "[] operation stands for calls to member functions get() and set()." 

但是,当我尝试运行这一行代码:

body.userData = animations[state[e].currentState]!!.keyFrames[frame]

我得到这个错误:

Exception in thread "LWJGL Application" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lcom.badlogic.gdx.graphics.g2d.TextureRegion;

但是,当我更改[]获取():

body.userData = animations[state[e].currentState]!!.keyFrames.get(frame)

一切都好起来。

PS:“frame”是角度,转换为Int。

UPD:我改变了我的代码

 val animation: Animation = anim[e].animations[state[e].currentState]!! val tex = animation.keyFrames[frame] // Get exception on this line anyway body[e].body.userData = tex 

“e”是来自Ashley的实体引用。 “body”,“anim”和“state”是Ashley组件映射器。

对于那些不知道LibGDX在这里的人来说,这里的Animation类keyFrames只是一个Java Array。

UPD 2:我注意到,只有当我使用这个构造函数时才会出现这个问题:

 Animation(float frameDuration, Array<? extends T> keyFrames) 

看起来像可互操作的问题。

铸造错误对象不能转换为TextureRegion

 public operator fun get(index: Int): T 

返回kotlin.Array的指定索引处的数组元素。

T[] keyFramesAnimation类中T类型的数组。


我用这种方式声明,我没有铸造错误/异常。 :

 lateinit var ani:Animation<TextureRegion> ani = Animation(.1f,TextureRegion(Texture("badlogic.jpg"))) val y= ani.keyFrames.get(0) // -> y is a TextureRegion 

替换为索引操作符

 val x=ani.keyFrames[0] // -> x is a TextureRegion 

然后分配给正文userData。

 val world = World(Vector2(10f,10f),false) val body = world.createBody(BodyDef()) body.userData = y // -> Either you use x or y you always get sprite var sprite=Sprite(body.userData as TextureRegion?)