Val 不能在 android buildTool 30.0.1 中重新分配

Mee*_*tel 3 android kotlin

我对 kotlin 不熟悉。我有一个应用程序,它的构建工具版本为 29.0.3,以下代码运行良好。

init {
    // Make sure that the view finder reference is valid
    val viewFinder = viewFinderRef.get()
            ?: throw IllegalArgumentException("Invalid reference to view finder used")

    // Initialize the display and rotation from texture view information
    viewFinderRotation = getDisplaySurfaceRotation(viewFinder.display)

    // Initialize public use-case with the given config
    previewUseCase = Preview(config)

    // Every time the view finder is updated, recompute layout
    previewUseCase.setOnPreviewOutputUpdateListener { output ->
        val vFinder = viewFinderRef.get() ?: return@setOnPreviewOutputUpdateListener

        // To update the SurfaceTexture, we have to remove it and re-add it
        val parent = viewFinder.parent as ViewGroup
        parent.removeView(viewFinder)
        parent.addView(viewFinder, 0)

        // Update internal texture
        viewFinder.surfaceTexture = output.surfaceTexture
        bufferRotation = output.rotationDegrees
        val rotation = getDisplaySurfaceRotation(viewFinder.display)
        updateTransform(vFinder, rotation, output.textureSize, viewFinderDimens)
    }

    // Every time the provided texture view changes, recompute layout
    viewFinder.addOnLayoutChangeListener { view, left, top, right, bottom, _, _, _, _ ->
        val vFinder = view as TextureView
        val newViewFinderDimens = Size(right - left, bottom - top)
        val rotation = getDisplaySurfaceRotation(viewFinder.display)
        updateTransform(vFinder, rotation, bufferDimens, newViewFinderDimens)
    }
}
Run Code Online (Sandbox Code Playgroud)

今天我试图将它更新到最新版本 30.0.1 并且它给了我调用val cannot be reassignedin line 的 错误viewFinder.surfaceTexture = output.surfaceTexture,没有任何建议。我试图按照此处的建议将 val 更改为 var ,但它没有解决该错误,我不知道我应该更改什么,如果有人可以帮助我,请告诉我。谢谢!

ian*_*ake 6

在 Android 30 SDK 中,setSurfaceTexture()有相应的@NonNull注解(你只能设置一个非 null SurfaceTexture)。但是,getSurfaceTexture()返回一个SurfaceTexture?(即,一个可为空的SurfaceTexture)。

var当类型不同时,Kotlin 不支持属性访问(并且可空性是 Kotlin 类型的重要部分),因此 Kotlin 只能val在您调用surfaceTexture属性时有效地为您提供等效项。

这意味着您需要明确使用setSurfaceTexture()来设置SurfaceTexture

viewFinder.setSurfaceTexture(output.surfaceTexture)
Run Code Online (Sandbox Code Playgroud)