Kotlin 如何在Try-Catch块中进行安全强制转换

Kotlin 如何在Try-Catch块中进行安全强制转换,kotlin,casting,try-catch,Kotlin,Casting,Try Catch,下面是如何使用Kotlin在Try-Catch块中安全地强制转换。这是一个语法问题。对于Kotlin,没有与此相关的答案,因此我将与大家分享,为其他人节省一些时间 通常,为了确保安全,人们使用以下格式: fun functionName() { if (propertyName is ClassName1) { val variableName2 = propertyName as ClassName1() propertyName.memberFunct

下面是如何使用Kotlin在Try-Catch块中安全地强制转换。这是一个语法问题。对于Kotlin,没有与此相关的答案,因此我将与大家分享,为其他人节省一些时间

通常,为了确保安全,人们使用以下格式:

fun functionName() {
    if (propertyName is ClassName1) {
        val variableName2 = propertyName as ClassName1()
        propertyName.memberFunction()
    }
}
以下代码将在出现编译错误时显示(我可能已经显示了太多,但我希望你们理解上下文):

生成输出错误读取:

Smart cast to 'Canvas' is impossible, 
because 'canvas' is a mutable property that could have been changed by this time

实际上,您必须将
作为
关键字放在括号内

以下代码将演示如何在try-catch块中实现智能强制转换:

    override fun run() {
        super.run()

        while(running) {
            try { 
                canvas = this.surfaceHolder.lockCanvas() 
                synchronized(surfaceHolder) {
                    this.gameView.update()
if (canvas is Canvas)
                    this.gameView.draw(canvas as Canvas) // Note change
                }
            } catch (e: Exception) {
            } finally {
                if(canvas != null){
                    try {
                        surfaceHolder.unlockCanvasAndPost(canvas)
                    } catch (e: Exception){
                        e.printStackTrace()
                    }
                }
            }
        }
    }
    override fun run() {
        super.run()

        while(running) {
            try { 
                canvas = this.surfaceHolder.lockCanvas() 
                synchronized(surfaceHolder) {
                    this.gameView.update()
if (canvas is Canvas)
                    this.gameView.draw(canvas as Canvas) // Note change
                }
            } catch (e: Exception) {
            } finally {
                if(canvas != null){
                    try {
                        surfaceHolder.unlockCanvasAndPost(canvas)
                    } catch (e: Exception){
                        e.printStackTrace()
                    }
                }
            }
        }
    }