Val cannot be reassigned in android buildTool 30.0.1

Viewed 634

I am not familiar with kotlin. I have one app which was have build tool version 29.0.3 and below code was working fine.

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)
    }
}

Today I am trying to update it to latest version 30.0.1 and its giving me error called val cannot be reassigned in line viewFinder.surfaceTexture = output.surfaceTexture, There no any suggestion for it. I have tried to change val to var as suggested here, but its not solving that error, I dont know what I should change, Let me know if anyone can help me for same. Thanks!

1 Answers

In the Android 30 SDK, setSurfaceTexture() has the appropriate @NonNull annotation (you can only set a non-null SurfaceTexture). However, getSurfaceTexture() returns a SurfaceTexture? (i.e., a nullable SurfaceTexture).

Kotlin does not support var property access when the types are different (and nullability is an important part of Kotlin typing) therefore Kotlin can only give you effectively the val equivalent when you call the surfaceTexture property.

This means that you need to explicitly use setSurfaceTexture() to set the SurfaceTexture:

viewFinder.setSurfaceTexture(output.surfaceTexture)
Related