Kotlin: why do I need to initialize a var with custom getter?

前端 未结 2 1053
臣服心动
臣服心动 2021-01-03 18:18

Why do I need to initialize a var with a custom getter, that returns a constant?

var greeting: String // Property must be initialized 
get() = \         


        
相关标签:
2条回答
  • 2021-01-03 18:54

    Your code does not have a custom setter, so it is equivalent to:

    var greeting: String
        get() = "hello"
        set(v) {field = v}  // Generated by default
    

    The default implementation of set uses field, so you've got to initialise it.

    By the same logic, you don't have to init the field if nether your set nor get use it (which means they are both custom):

    var greeting: String  // no `field` associated!
        get() = "hello"
        set(v) = TODO()
    
    0 讨论(0)
  • 2021-01-03 18:59

    Reason behind this is Backing field. When you create val with custom getter that does not use field identifier to access its value, then backing field is not generated.

    val greeting: String
        get() = "hello"
    

    If you do, then backing field is generated and needs to be initialized.

    val greeting: String // Property must be initialized
        get() = field
    

    Now with var. Since backing filed is generated by default, it must be initialized.

    var greeting: String // Property must be initialized
        get() = "hello"
    

    For this to work for var without initialization, you must provide a custom setter to prevent generation of backing field. For example:

    var storage: String = ""
    var greeting: String
        get() = "hello"
        set(value) { storage = value}
    
    0 讨论(0)
提交回复
热议问题