如何在Kotlin中实现需要另一个属性的惰性属性?
我需要一个矩形,需要在调用时初始化 这是我的密码如何在Kotlin中实现需要另一个属性的惰性属性?,kotlin,lazy-initialization,kotlin-delegate,Kotlin,Lazy Initialization,Kotlin Delegate,我需要一个矩形,需要在调用时初始化 这是我的密码 class EpheButton private constructor( private val text: String, private val x: Float, private val y: Float, private val projectionMatrix: Matrix4) : Disposable { private val spriteBatch: SpriteBatch = SpriteBa
class EpheButton private constructor(
private val text: String,
private val x: Float,
private val y: Float,
private val projectionMatrix: Matrix4) : Disposable {
private val spriteBatch: SpriteBatch = SpriteBatch()
private val bitmapFont: BitmapFont = BitmapFont()
private val shapeRenderer: ShapeRenderer = ShapeRenderer()
private val textWidth: Float
private val textHeight: Float
private val rectangle :Rectangle by lazy { Rectangle(x, y, textWidth, textHeight) }
init {
bitmapFont.data.setScale(2f)
bitmapFont.region.texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear)
bitmapFont.color = Color.BLUE
val layout = GlyphLayout()
layout.setText(bitmapFont, text)
textWidth = layout.width
textHeight = layout.height
}
我得到了行private val rectangle:rectangle by lazy{rectangle(x,y,textWidth,textweath)}
的错误,这表示:
必须初始化变量“textWidth”
必须初始化变量“textHeight”
但是我已经在init{}
code块上初始化了它们
我做错了什么?在kotlin中,您必须在使用变量之前对其进行初始化,您正在对矩形使用惰性初始值设定项,但编译器不知道textWidth和textHeight 所以课堂看起来是这样的
class EpheButton private constructor(
private val text: String,
private val x: Float,
private val y: Float,
private val projectionMatrix: Matrix4) : Disposable {
private val spriteBatch: SpriteBatch = SpriteBatch()
private val bitmapFont: BitmapFont = BitmapFont()
private val shapeRenderer: ShapeRenderer = ShapeRenderer()
private val textWidth: Float
private val textHeight: Float
init {
bitmapFont.data.setScale(2f)
bitmapFont.region.texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear)
bitmapFont.color = Color.BLUE
val layout = GlyphLayout()
layout.setText(bitmapFont, text)
textWidth = layout.width
textHeight = layout.height
}
private val rectangle :Rectangle by lazy { Rectangle(x, y, textWidth, textHeight) }
更新:-
为什么初始化顺序在这里?
我们可以把这种古怪的行为称为科特林的行为。当我们更改init block和变量声明的顺序时,我们违反了这个规则
来自科特林官方文件:-
Kotlin的类型系统旨在从中消除NullPointerException
我们的代码。NPE的唯一可能原因可能是
除了这四个条件之外,它始终确保在编译时初始化变量。因此,与我们的情况相同,它只是确保使用的变量必须在使用之前初始化 顺序很重要,这不是很奇怪吗?我认为可以保证在创建对象时调用init代码块。kotlin编译器不知道这一点吗?我只是kotlin的初学者,所以不知道太多细节,但我试图解释我对这种行为的最佳解释,请查看更新的答案。如果您发现任何错误或冲突,请毫不犹豫地否决答案。:)