预期的属性获取器或设置器

Kim*_*euk 4 android kotlin

我想在一个类中使用位图变量。它使“属性获取器或设置器预期”错误。问题是什么?错误显示在“ bmp?:位图=空”。我该如何解决这个问题?

而且我不明白为什么我必须对类中的私有属性使用getter或setter。

class MyView(context: Context?) : View(context) {
    private var bmp? : Bitmap = null

    init {
        bmp = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.drawColor(Color.BLUE)
        canvas?.drawBitmap(bmp,10f,10f, null)
    }
}
Run Code Online (Sandbox Code Playgroud)

Jee*_*ede 7

问题是您将使用安全调用运算符创建Nullable对象,但是语法错误。尽管放置?在变量上,您仍需要将其放置在引用类型上。

检查正确的语法:

private var bmp : Bitmap? = null
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用如下所示的安全调用运算符访问此变量:

bmp?.someMethodCall() // This line will never throw you null pointer exception because of ? (Safe call operator)
Run Code Online (Sandbox Code Playgroud)

在这里查看更多信息