Sunday, 31 December 2017

Kotlin: Any: Super class of all classes

‘Any’ is the default super class for all the classes in Kotlin. All the classes in kotlin implicitly inherits the properties, functions from Any class.


Previous                                                 Next                                                 Home

Saturday, 30 December 2017

Kotlin: How to create Object

Unlike Java, 'new' keyword is not required to define an object.

Syntax
var objectName  = ClassName(arguments)

Ex
var emp1 = Employee("Shwetha")
var emp2 = Employee("Krishna", "G")

ConstructorDemo.kt

class Employee {

 var firstName: String = ""
 var lastName: String = ""

 constructor(fName: String) {
  this.firstName = fName
  this.lastName = fName
 }

 constructor(fName: String, lName: String) {
  this.firstName = fName
  this.lastName = lName
 }
}

fun printEmployee(emp: Employee) {
 println("firstName : ${emp.firstName}, lastName : ${emp.lastName}")
}

fun main(args: Array<String>) {
 var emp1 = Employee("Shwetha")
 var emp2 = Employee("Krishna", "G")

 printEmployee(emp1)
 printEmployee(emp2)

}

Output

firstName : Shwetha, lastName : Shwetha
firstName : Krishna, lastName : G



Previous                                                 Next                                                 Home

Friday, 29 December 2017

Kotlin: Define private primary constructor

By specifying the 'private' access specifier in the class header, you can define a private primary constructor.

PrivateConDemo.kt

class Employee private constructor(var firstName: String) {

 var lastName: String = ""

 constructor(fName: String, lName: String) : this(fName) {
  this.lastName = lName
 }
}

fun printEmployee(emp: Employee) {
 println("firstName : ${emp.firstName}, lastName : ${emp.lastName}")
}

fun main(args: Array<String>) {
 var emp1 = Employee("Shwetha", "kam")

 printEmployee(emp1)

}

Output

firstName : Shwetha, lastName : kam


Previous                                                 Next                                                 Home

Kotlin: Default constructor

If you do not declare any constructor (primary or secondary) in your non-abstract class, kotlin will generate a default primary constructor with no arguments.

What is the access scope of this primary constructor?
The default constructor has public scope by default.


Previous                                                 Next                                                 Home

Thursday, 28 December 2017

Kotlin: Passing default values to primary constructor

You can pass default values to the primary constructor.

Ex:
class Employee(var firstName: String = "Krishna", var lastName: String = "Gurram") {

}

Above snippet defines a primary constructor to the class Employee, with default values.

var emp1 = Employee()
Since we do not pass any arguments to the constructor, firstName and lastName are initialized with default values. 'firstName' is initialized with 'Krishna' and lastName is initialized with 'Gurram'

var emp2 = Employee("Rachit")
Since we passed only first argument, 'firstName' is assigned with value 'Rachit' and 'lastName' is assigned with value 'Gurram'

var emp3 = Employee("Shwetha", "kam")
'firstName' is assigned with value 'Shwetha' and 'lastName' is assigned with value 'Kam'.    

ConstructorDemo.kt

class Employee(var firstName: String = "Krishna", var lastName: String = "Gurram") {

}

fun printEmployee(emp: Employee) {
 println("firstName : ${emp.firstName}, lastName : ${emp.lastName}")
}

fun main(args: Array<String>) {
 var emp1 = Employee()
 var emp2 = Employee("Rachit")
 var emp3 = Employee("Shwetha", "kam")

 printEmployee(emp1)
 printEmployee(emp2)
 printEmployee(emp3)

}

Output

firstName : Krishna, lastName : Gurram
firstName : Rachit, lastName : Gurram
firstName : Shwetha, lastName : kam


Previous                                                 Next                                                 Home

Wednesday, 27 December 2017

Kotlin: Secondary Constructors

Kotlin class can have more than one secondary constructors.

How to define secondary constructor?
You should use the keyword ‘constructor’ to define secondary constructor.

Syntax
constructor(arguments){

}

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

 constructor(firstName: String) {
  this.firstName = firstName
  this.lastName = firstName
 }

 constructor(firstName: String, lastName: String) {
  this.firstName = firstName
  this.lastName = lastName
 }
}

fun printEmployee(emp: Employee) {
 println("firstName : ${emp.firstName}, lastName : ${emp.lastName}")
}

fun main(args: Array<String>) {
 var emp1 = Employee("Hareesh", "Seeram")
 var emp2 = Employee("Praneeth")

 printEmployee(emp1)
 printEmployee(emp2)

}

Output

firstName : Hareesh, lastName : Seeram
firstName : Praneeth, lastName : Praneeth

Primary constructor must be called from secondary constructor explicitly. What I mean is, if a class has primary constructor, then the secondary constructor must delegate to the primary constructor either directly (or) indirectly using other secondary constructors.
class Employee(var firstName: String) {
         ....
         ....
        
         constructor(fName: String, lName: String) : this(fName) {
                 this.lastName = lName
                 this.id = ""
         }
}

In the above example, Employee class has a primary constructor, We are calling primary constructor using 'this' keyword, while defining secondary constructor.


ConstructorDemo.kt

class Employee(var firstName: String) {
 var lastName: String = ""
 var id: String = ""

 constructor(fName: String, lName: String) : this(fName) {
  this.lastName = lName
  this.id = ""
 }

 constructor(fName: String, lName: String, id: String) : this(fName) {
  this.lastName = lName
  this.id = id
 }
}

fun printEmployee(emp: Employee) {
 println("id : ${emp.id}, firstName : ${emp.firstName}, lastName : ${emp.lastName}")
}

fun main(args: Array<String>) {
 var emp1 = Employee("Krishna")
 var emp2 = Employee("Hareesh", "Seeram")
 var emp3 = Employee("Praneeth", "Sai", "123")

 printEmployee(emp1)
 printEmployee(emp2)
 printEmployee(emp3)

}


Output

id : , firstName : Krishna, lastName : 
id : , firstName : Hareesh, lastName : Seeram
id : 123, firstName : Praneeth, lastName : Sai


Previous                                                 Next                                                 Home

Tuesday, 26 December 2017

Is Kotlin class requires body?

Body is optional for kotlin class. Below classes are valid in kotlin.

Ex
class DocService
class Student
Previous                                                 Next                                                 Home

Sunday, 24 December 2017

Kotlin: Constructors

Kotlin classes have a primary constructor and one or more secondary constructors. Constructors are defined using constructor keyword.

Primary Constructor
Primary constructor is defined as part of the class header.

Ex
class Employee constructor(fName: String, lName: String) {
         ....
         ....
}

Employee.kt
class Employee constructor(fName: String, lName: String) {
 init{
  println("fName : $fName, lName : $lName")
 }
}

Main.kt
fun main(args: Array<String>) {
 var emp1 = Employee("Hareesh", "Seeram")
}
Output
fName : Hareesh, lName : Seeram

init{} is equivalent to the initializer block of java, it is used to place the object initialization code. This block is called on every object instantiation.

You can omit the constructor keyword while defining primary constructor, if the constructor do not have any modifier (or) annotation associated with it.


Employee.kt
class Employee (fName: String, lName: String) {
 init{
  println("fName : $fName, lName : $lName")
 }
}

Defining member variables as part of primary constructor
If you add the keyword ‘var’/’val’ to the type parameter in primary constructor, it creates a field in class.


Main.kt
class Employee(var firstName: String, var lastName: String) {

}

fun main(args: Array<String>) {
 var emp1 = Employee("Hareesh", "Seeram")

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

Output

firstName : Hareesh, lastName : Seeram

In the above snippet, I defined firstName and lastName fields as part of primary constructor




Previous                                                 Next                                                 Home

Kotlin: Body of the class is optional

In kotlin, you no need to define the body to a class, it is optional.

Employee.kt
class Employee

As you see, I defined Employee class with no body.

Previous                                                 Next                                                 Home

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