Kotlin中的get和[]调用有什么区别?
问题描述:
我使用Kotlin语言+ LibGDX库制作游戏。Kotlin中的get和[]调用有什么区别?
科特林版本: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”是阿什利实体refrence。 “body”,“anim”和“state”是Ashley组件映射器。
对于那些不知道LibGDX在这里的人是动画类 这里的keyFrames只是一个Java Array。
UPD 2: 我注意到,只有当我使用这个构造发生这个问题:
Animation(float frameDuration, Array<? extends T> keyFrames)
貌似互操作问题。
答
铸造误差对象不能的kotlin.Array
指定索引处被转换为TextureRegion
public operator fun get(index: Int): T
返回的数组元素。
T[] keyFrames
是Animation
类中的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
然后分配到身体用户数据。
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?)
'keyFrames'的类型是什么? –
您正在使用哪种LibGDX版本? – Aryan
@AbhishekAryan 1.9。6 – icarumbas