这里是如何使用Kotlin在Try-Catch块中安全投射。这是一个语法问题。对于Kotlin,没有与此相关的答案,因此我将分享给大家,以节省一些时间。
通常,为了安全起见,人们使用以下格式:
fun functionName() {
if (propertyName is ClassName1) {
val variableName2 = propertyName as ClassName1()
propertyName.memberFunction()
}
}
以下代码将在出现编译错误时显示(我可能显示的太多了,但是我希望你们理解上下文):
import android.graphics.Canvas
import android.view.SurfaceHolder
import java.lang.Exception
class MainThread(surfaceHolder: SurfaceHolder, gameView: GameView): Thread() {
private lateinit var surfaceHolder: SurfaceHolder
private lateinit var gameView: GameView
private var running: Boolean = false
private var canvas: Canvas? = null
override fun run() {
super.run()
while(running) {
try {
canvas = this.surfaceHolder.lockCanvas()
synchronized(surfaceHolder) {
this.gameView.update()
this.gameView.draw(canvas) // Error arises at this line
}
} catch (e: Exception) {
} finally {
if(canvas != null){
try {
surfaceHolder.unlockCanvasAndPost(canvas)
} catch (e: Exception){
e.printStackTrace()
}
}
}
}
}
Build Output Error读取:
Smart cast to 'Canvas' is impossible,
because 'canvas' is a mutable property that could have been changed by this time
答案 0 :(得分:0)
实际上,您必须将as
关键字放在括号内。
以下代码将显示如何在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()
}
}
}
}
}