簡體   English   中英

Kotlin中的get和[]調用有什么區別?

[英]What's difference between get and [] call in 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;

但是,當我將[]更改為get()時:

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

一切都很好。

PS:“框架”是角度,轉換為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是什么的人來說,動畫類keyFrames只是一個Java數組。

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?)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM