简体   繁体   中英

Unable to change value of an initialised primitive type using Kotlin

I can't change the value of an initialised variable.

I tried googling the problem to no avail. Float is a primitive type so it cannot be lateinit.

class RegistrationActivity : AppCompatActivity() {

    val scale = 0f

    public override fun onStart() {
        super.onStart()
        scale = this.resources.displayMetrics.density
    }
}

I expect to be able to initialise the "scale" variable outside of a method body so that it can be used by other methods, but in my attempt I'm met with the "Val cannot be reassigned" as an error inside of the "onStart()" method when I hover over "scale" in "scale = this.resources.displayMetrics.density".

You need to use

var scale = 0f

instead of

val scale = 0f

val is immutable and it can not change over the time

var can change over the time

If you came from java.

val scale = 0f will be the equivalent for

final float scale = 0f;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM