Sunday, 24 December 2017

Kotlin: lateinit : Late initialized properties

By default, kotlin do not allow uninitialized properties. You must initialize them at the time of declaration (or) in the constructor. Let me explain with an example.

HelloWorld.kt
class Employee{
 var id : String
 var name : String
 var city : String
}

When you try to compile above program, you will end up in below error.

         ERROR: Property must be initialized or be abstract (2, 2)
         ERROR: Property must be initialized or be abstract (3, 2)
         ERROR: Property must be initialized or be abstract (4, 2)
        
How to resolve above problem?
There are three ways:
         a. Initialize the variables at the time of declaration
         b. Define the variables in constructor
         c. Use late initialization


Initialize the variables at the time of declaration
class Employee {
 var id: String = "123"
 var name: String = "Krishna"
 var city: String = "Ongole"
}

Define the variables in constructor
class Employee {
 var id: String
 var name: String
 var city: String

 constructor() {
  id = "123"
  name = "Krishna"
  city = "Ongole"
 }
}

Use late initialization
By using lateinit keyword, we can inform kotlin that this variable will be initialized at later point of time.

class Employee {
 lateinit var id: String
 lateinit var name: String
 lateinit var city: String
}

Can I access lateint property before initialization?
No, If you try to access a lateinit property before initialization, you will end up in 'UninitializedPropertyAccessException'

HelloWorld.kt
class Employee {
 lateinit var id: String
 lateinit var name: String
 lateinit var city: String
}

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

 println("Id : ${obj.id}")
}


When you try to run above program, you will end up in below exception.

Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property id has not been initialized
         at Employee.getId(HelloWorld.kt:2)
         at HelloWorldKt.main(HelloWorld.kt:10)

To resolve the error define the lateinit properties before accessing.

HelloWorld.kt

class Employee {
 lateinit var id: String
 lateinit var name: String
 lateinit var city: String
}

fun main(args: Array<String>) {
 var obj = Employee()
 
 obj.id = "123"

 println("Id : ${obj.id}")
}

Output
Id : 123





Previous                                                 Next                                                 Home

Saturday, 23 December 2017

Kotlin: const vs val

'const' keyword is used to define compile time constants,I.e, the value of the const variable is known at compile time. Whereas ‘val’ is used to define constants at run time.

For example, you can’t define a const like below.

const val PICon = getPI()

When you try to compile the kotlin program with above statement, you will endup in below error.
‘Const 'val' has type 'Unit'. Only primitives and String are allowed’. 

This is because, getPI() is evaluated at run time and assign the value to PICon, but const is used to define the constant at compile time.

Find the below working application.

HelloWorld.kt
const val VENDOR_NAME = "Self Learning Java blog"
val PICon = getPI()

fun getPI(): Double {
 return 3.14
}

fun main(args: Array<String>) {
 println("Vendor Name $VENDOR_NAME")
 println("Value of PI : $PICon")
}


Output

Vendor Name Self Learning Java blog
Value of PI : 3.14




Previous                                                 Next                                                 Home

Thursday, 21 December 2017

Kotlin: const: Compile time constants

You can define the compile time constants using ‘const’ keyword.

Ex
const val VENDOR_NAME = "Self Learning Java blog"

HelloWorld.kt
const val VENDOR_NAME = "Self Learning Java blog"
const val PI = 3.14

fun main(args: Array<String>) {
 println("Vendor Name $VENDOR_NAME")
 println("Value of PI : $PI")
}

Output

Vendor Name Self Learning Java blog
Value of PI : 3.14

While defining compile time constants, the properties must fulfil below preconditions.

a.   Top-level or member of an object
b.   Initialized with a value of type String or a primitive type
c.   No custom getter



Previous                                                 Next                                                 Home

Kotlin: Member properties must be initialized

In kotlin, member properties either initialized (or) must be declared as abstract. Let’s see it by an example.

Employee.kt
class Employee {
 private var firstName: String
 private var lastName: String

 fun getFirstName(): String {
  return firstName
 }

 fun getLastName(): String {
  return lastName
 }

 fun setFirstName(firstName: String) {
  this.firstName = firstName
 }

 fun setLastName(lastName: String) {
  this.lastName = lastName
 }
}


Try to compile above program, you will end up with below error.
C:\>kotlinc Employee.kt
Employee.kt:2:2: error: property must be initialized or be abstract
        private var firstName: String
 ^
Employee.kt:3:2: error: property must be initialized or be abstract
        private var lastName: String

How to get rid of above error?
There are two ways, either initialize the property (or) make the property as abstract.

Way1: Initialize the properties firstName and lastName


Employee.kt
class Employee {
 private var firstName: String = ""
 private var lastName: String = ""

 fun getFirstName(): String {
  return firstName
 }

 fun getLastName(): String {
  return lastName
 }

 fun setFirstName(firstName: String) {
  this.firstName = firstName
 }

 fun setLastName(lastName: String) {
  this.lastName = lastName
 }
}

Way 2: Make the properties as abstract

Employee.kt
abstract class Employee {
 abstract var firstName: String
 abstract var lastName: String
}




Previous                                                 Next                                                 Home

Kotlin: Define member functions of class

Functions in kotlin are defined using ‘fun’ keyword.

Ex:
fun square(x : Int) : Int{
         return x*x
}

Above code snippet define a function named ‘square’, it takes one argument of type Int and return the integer.

Employee.kt
class Employee {
 private var firstName: String = ""
 private var lastName: String = ""

 fun getFirstName(): String {
  return firstName
 }

 fun getLastName(): String {
  return lastName
 }

 fun setFirstName(firstName: String) {
  this.firstName = firstName
 }

 fun setLastName(lastName: String) {
  this.lastName = lastName
 }
}

Main.kt
fun main(args: Array<String>) {

 var emp1 = Employee()

 emp1.setFirstName("Chamu")
 emp1.setLastName("Gurram")

 println("firstName : ${emp1.getFirstName()}")
 println("lastName : ${emp1.getLastName()}")
}

Output
firstName : Chamu
lastName : Gurram



Previous                                                 Next                                                 Home

Wednesday, 20 December 2017

Kotlin: getters & setters to properties

In my previous post, I explained how to define properties, in addition to defining, we can add getter and setter methods to the properties.

Syntax
var <propertyName>[: <PropertyType>] [= <property_initializer>]
    [<getter>]
    [<setter>]

PropertyType, getter and setter are optional while defining a property.

HelloWorld.kt
class Employee {
 var name: String = "Krishna"
  get() = field
  set(value) {
   field = value
  }

 var age : Int = 28
  get() = field
  set(value) {
   field = value
  }

 val orgID = "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

As you notify the code, I used ‘field’ identifier to refer backing field. By convention setter method takes ‘value’ as argument name, you can use any name.

Why do I require getter and setter methods?
Getter and setter methods are used to transform/validate the the data before sending/setting the information.

         var age : Int = 28
                 get() = field
                 set(value) {
                          if(value < 0 || value > 100)
                                  field = 3
                 }

For example, in the above snippet, setter method validate the age before setting it to the property age. If user sets the age to <0 (or) > 100, age will be set to 3. Find the below working application.


HelloWorld.kt
class Employee {
 var name: String = "Krishna"
  get() = field
  set(value) {
   field = value
  }

 var age: Int = 28
  get() = field
  set(value) {
   if (value < 0 || value > 100)
    field = 3
  }

 val orgID = "ORG1234"

}

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

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

 emp.age = -100
 println("\nAfter setting the age to -100")

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

Output
name : Krishna
age : 28
orgID : ORG1234

After setting the age to -100
name : Krishna
age : 3
orgID : ORG1234

Kotlin provides default getter and setter methods for mutable (Properties defined with var keyword) properties, where as it provides only getter method for immutable (Properties defined with val keyword) properties.

var name = "Krishna" //  has type String and a default getter and setter
val orfID = "orf1234" // has type String and a default getter





Previous                                                 Next                                                 Home

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