“This modifier can be used on var properties declared inside the body of a class (not in the primary constructor, and only when the property does not have a custom getter or setter), as well as for top-level properties and local variables.”
it means lateinit modifier can be used inside the body of a class as well as for top-level properties and local variables.
As I know, in kotlin we have a terminology “Property” that consists of backing field (the only “field” terminology I know)
So what is “local variable” in kotlin? is it different with property?
A local variable is a variable within a visibility scope, so it can be accessed locally only.
In the same page, perimeter is a property, rectangle is a local variable:
class Rectangle(val height: Double, val length: Double) {
val perimeter = (height + length) * 2
}
fun main() {
val rectangle = Rectangle(5.0, 2.0)
println("The perimeter is ${rectangle.perimeter}")
}
so rectangle can be called as local property? what diff between local property and local variable? after reading the guide, I think it seem to be the same but if it’s the same, why the guide said like “for top-level properties and local variables”?
Properties are something that exist on an object for as long as that object exists. Local variables can exist inside functions or in a constructor. Local variables inside a function are only visible inside that function, and disappear when the function ends. Local variables in a constructor are visible to any initialization code inside the class body (initializing properties or init blocks), and disappear when the class finishes being created.
Please note this is not really a Kotlin jargon, it is rather an industry standard. Most languages have local variables and either properties, fields or both. Of course, there are some differences between languages, for example in Kotlin constructor params (so local vars) are not scoped to a function, but to a class body (let’s simplify). But generally, these concepts are rather common.