google-developer-training / basic-android-kotlin-compose-birthday-card-app

Apache License 2.0
121 stars 95 forks source link

kotlin getter() confusion #229

Closed juanqiuxiaoxiao1 closed 1 year ago

juanqiuxiaoxiao1 commented 1 year ago

URL of codelab https://developer.android.com/codelabs/basic-android-kotlin-compose-classes-and-objects?continue=https%3A%2F%2Fdeveloper.android.com%2Fcourses%2Fpathways%2Fandroid-basics-compose-unit-2-pathway-1%23codelab-https%3A%2F%2Fdeveloper.android.com%2Fcodelabs%2Fbasic-android-kotlin-compose-classes-and-objects#4

In which task and step of the codelab can this issue be found?

step 5, define class properties Describe the problem New to Kotlin, there's a diagram in the codelab saying that getters in kotlin should define like this:

get() {
    <body>
    <return statement>
}

so I tried:

fun main() {
    val smartTV = SmartTV()
    println(smartTV.speakerVolume)
    smartTV.speakerVolume = 100
    println(smartTV.speakerVolume)
}

class SmartTV {
    var speakerVolume = 2
    get() = {
        println("Getter...")
        return field
    }
    set(value) {
        field = 0    
    }
}

Kotlin playground throws two errors: "Type mismatch: inferred type is () -> [Error type: Return not allowed] but Int was expected " and "'return' is not allowed here"

Plus there's no example in the codelab that explains how to modify getter.

Could you explain why it won't compile, thanks.

Steps to reproduce?

  1. Go to...
  2. Click on...
  3. See error...

Versions Android Studio version: API version of the emulator:

Additional information Include screenshots if they would be useful in clarifying the problem.

juanqiuxiaoxiao1 commented 1 year ago

Just found that there's a redundant '=' in the getter(). Removing that will work.