Kotlin Code Pills —OOP-Properties 1
Kotlin is an Object-Oriented language and in this article, we will look into the basics of Properties in Kotlin.
property = field + accessors
Here let’s look properties in Java
public class JavaClass {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
In Java, to get or set the data from properties we need to define getter and setter methods, but in Kotlin getter and setter methods generated automatically when you define a property like below
class KotlinClass(
var name: String
)
In Kotlin you can create two types of properties
- val: Read-Only Property
- var: Mutable Property
With more in details;
val= field + getter
var= field + getter + setter
In Kotlin example above, to get and set name
the property like below;
kotlinClass.name // getter
kotlinClass.name = "John" //setter
Property without field
In Kotlin you can also create property without field like below by using get and set functions
class Rectangle(val height: Int, val width: Int) { val isSquare: Boolean
get() {
return height == width
}}
and you can use like that
val rectangle = Rectangle(1,3)
println(rectangle.isSquare) //false
Default Accessors
In Kotlin you can also set some default value in Properties.
class KotlinClass(
var name: String = "John"
)
In this code pills, we see how we define properties in Kotlin and read-only & mutable properties. In the next code pills, we will go thought some more details in Properties. See you in the next Kotlin Code pills.