Monday, 18 December 2017

Kotlin: Declaring properties

You can define properties in a class. Properties can be mutable (or) immutable (Can't be changed once defined).

How to define mutable properties?
Mutable properties are defined using ‘var’ keyword.

Ex
var name : String = "Krishna"

How to define immutable properties?
Immutable properties are defined using ‘val’ keyword.

Ex
val name : String = "Krishna"

class Employee{
         var name : String = "Krishna"
         var age : Int = 28
         val orgID : String = "ORG1234"
}

As you notify Employee class, I defined name and age as mutable properties, orgID as immutable property.

How to access properties in a class?
By defining an object, you can access the properties of a class. ‘.’ Notation is used to access the instance property of a class.

Syntax
objectName.propertyName

HelloWorld.kt
class Employee {
 var name: String = "Krishna"
 var age: Int = 28
 val orgID: String = "ORG1234"
}

fun main(args: Array<String>) {
 var emp = Employee()

 println("name : ${emp.name}")
 println("age : ${emp.age}")
 println("orgID : ${emp.orgID}")
}

Output

name : Krishna
age : 28
orgID : ORG1234

You no need to add property type while defining a property, it will be inferred by kotlin environment. But adding type improves the program readability.

class Employee {
 var name = "Krishna"
 var age = 28
 val orgID = "ORG1234"
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment