HelloCW
HelloCW

Reputation: 2235

What are different between Code 1 and Code 2 in Kotlin?

The code 1 is from a sample project, and I modify some code and change it to code 2, and the code 2 can also run correctly.

What are different between Code 1 and Code 2 in Kotlin? Thanks!

Code 1

data class ForecastList(val id: Long, val city: String, val country: String, val dailyForecast: List<Forecast>) {

    val size: Int
        get() = dailyForecast.size

    operator fun get(position: Int) = dailyForecast[position]
}

Code 2

data class ForecastList(val id: Long, val city: String, val country: String, val dailyForecast: List<Forecast>) {

    val size: Int = dailyForecast.size

    operator fun get(position: Int) = dailyForecast[position]
}

Upvotes: 0

Views: 140

Answers (1)

Laurence Gonsalves
Laurence Gonsalves

Reputation: 143094

The first will evaluate dailyForecast.size at construction, store the value in a backing field, and create an accessor that returns the value of this backing field.

The second will not create a backing field, but will instead create an accessor that returns the evaluates the expression dailyForecast.size every time you get the size.

Upvotes: 3

Related Questions