Category: Kotlin

Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of Kotlin’s standard library depends on the Java Class Library, but type inference allows its syntax to be more concise.

Kotlin Abstract Classes with Examples

Kotlin Abstract Classes with Examples

An abstract class is a class that cannot be instantiated. We create abstract classes to provide a common template for other classes to extend and use.

Declaring an Abstract Class

You can declare an abstract class using the abstract keyword –

abstract class Vehicle

An abstract class may contain both abstract and non-abstract properties and functions. You need to explicitly use the abstract keyword to declare a property or function as abstract –

abstract class Vehicle(val name: String,
                       val color: String,
                       val weight: Double) {   // Concrete (Non Abstract) Properties

    // Abstract Property (Must be overridden by Subclasses)
    abstract var maxSpeed: Double

    // Abstract Methods (Must be implemented by Subclasses)
    abstract fun start()
    abstract fun stop()

    // Concrete (Non Abstract) Method
    fun displayDetails() {
        println("Name: $name, Color: $color, Weight: $weight, Max Speed: $maxSpeed")

Any subclass that extends the abstract class must implement all of its abstract methods and properties, or the subclass should also be declared as abstract.

If you recall from the Kotlin Inheritance tutorial, you need to annotate a class as open to allow other classes to inherit from it. But, you don’t need to do that with abstract classes. Abstract classes are open for extension by default.

Similarly, abstract methods and properties are open for overriding by default.

But, If you need to override a non-abstract method or property, then you must mark it with the open modifier.

Extending from an Abstract class

Following are two concrete classes that extend the Vehicle abstract class and override its abstract methods and properties –

class Car(name: String,
          color: String,
          weight: Double,
          override var maxSpeed: Double): Vehicle(name, color, weight) {

    override fun start() {
        // Code to start a Car
        println("Car Started")

    override fun stop() {
        // Code to stop a Car
        println("Car Stopped")
class Motorcycle(name: String,
           color: String,
           weight: Double,
           override var maxSpeed: Double): Vehicle(name, color, weight) {

    override fun start() {
        // Code to Start the Motorcycle
        println("Bike Started")

    override fun stop() {
        // Code to Stop the Motorcycle
        println("Bike Stopped")

Let’s now write some code to test our abstract and concrete classes in the main method –

fun main(args: Array<String>) {

    val car = Car("Ferrari 812 Superfast", "red", 1525.0, 339.60)
    val motorCycle = Motorcycle("Ducati 1098s", "red", 173.0, 271.0)



Here is the output of the above main() method –

# Output
Name: Ferrari 812 Superfast, Color: red, Weight: 1525.0, Max Speed: 339.6
Name: Ducati 1098s, Color: red, Weight: 173.0, Max Speed: 271.0
Car Started
Bike Started


Abstract classes help you abstract out common functionality into a base class. It may contain both abstract and non-abstract properties and methods. An abstract class is useless on its own because you cannot create objects from it. But, other concrete (non-abstract) classes can extend it and build upon it to provide the desired functionality.

A Guide on How to Write a Clean Code

A Guide on How to Write a Clean Code

In this article, I’m going to talk about writing clean code in general and then end up with some examples. As an Android developer having a clean code has always been challenging for me which needs lots of effort and that’s just coding and coding.

Rules We Should Follow

  1. Ignore duplication (imply DRY principle-Don’t Repeat Yourself)
  2. Minimize entities, classes, and functions (avoid repetition)
  3. It should be readable and simple
  4. Be testable as it makes your code flexible and maintainable
  5. Follow SOLIDprinciples

S = Single-responsibility principle: A class should only have one purpose.

O = Open-closed principleA class should be open for extension, but closed for modification.

L = Liskov substitution principleAbstraction should be able to provide all needs of child class.

I = Interface segregation principleSmall interface is better than big one.

D = Dependency Inversion Principle: A class should depend on abstraction, not implementation.

6. Be careful with dependencies

As many as possible try to have one-directional dependency. When dependency goes in multiple directions, things get much more complicated which makes hard to update and change.

7. Don’t hardcode

Define constant or use variables instead of hardcoding the values which will not only help readability but also make it easy to change if it is being used at multiple places.

Now let’s start writing Clean Code 🚀 …

Valid Names

Naming is one of the hardest parts of programming and may take time to choose, but it is a strong way to convey your code’s intent to other developers who read them in the future which must show the purpose of that class, function, or variable and even tell what is going to do. Don’t append prefixes or type information. I always have a checklist in my mind as listed below which assures me that a name has been chosen well:

  • Are the variables named according to the convention (camelCase, PascalCase, etc)?.
  • Does the name have an appropriate length to ensure that no one will be confused by it?.
  • Are the name of variables clear about what they hold?.
  • Are the names meaningful, searchable, and easy to pronounce?.

Class names should not only be names (not verbs) but also should have the PascalCase convention. On the other hand, method names should be verbs or phrase verbs and follow the camelCase convention. The same rules apply to variable names.

Functions and Methods

Following S from SOLID principles, let functions and methods perform only one task which should be small. If the function arguments are too many, you should review your code and maybe pack them into an object or divide that task between some other functions. Prefer possible exceptions to return error codes and extract error handling try catch into their own function.


We should use comments only when it is necessary, not to explain bad code. Writing lengthy comments will not help us in changing our code into a clean one. If the code is bad, we should solve it by improving the code, not by adding instructions on how to use it, but it doesn’t mean that you shouldn’t use comments at all, sometimes it is important such as dealing with third party APIs where you need to explain some behavior.

Code Appearance

It might look unimportant at first glance, but it is of high importance to write your code with a well-organized format which makes it readable such as:

  • Do not write everything in a single line. Give proper whitespace, indentation, or line breaks in your code.

Indentation styles assist in identifying control flow and blocks of code. In some programming languages, indentation is used to delimit logical blocks of code; correct indentation in these cases is more than a matter of style. In other languages, indentation and white space do not affect function, although logical and consistent indentation makes code more readable. (Inspired by WIKIPEDIA)

  • Instance variables should be declared at the top of the class.
  • If functions are calling each other (dependent functions) they should be close while putting the caller at first.
  • It is often helpful to align similar elements vertically, to make typo-generated bugs more obvious.


The importance of Test code is equal to producing the code and of course, while writing tests you might find some bugs. However, it can sometimes be quite difficult to write a good test for a particular piece of code which is a result of a badly designed and untestable code. Testing is almost like coding for the second time so follow all the previous rules for writing a good test as well which should be as per below :

  • One assert and single concept per test
  • Easy to write and readable (simplicity)
  • Fast
  • Independent

To conclude, I hope this article could be helpful to write a better code although it is important to keep practicing and learning in this field 😃 …

Kotlin Infix Notation - Make function calls more intuitive

Kotlin Infix Notation – Make function calls more intuitive

Kotlin supports method calls of a special kind, called infix calls.

You can mark any member function or extension function with the infix modifier to allow it to be called using infix notation. The only requirement is that the function should have only one required parameter.

Infix notations are used extensively in Kotlin. If you’ve been programming in Kotlin, chances are that you’ve already used infix notations.

Following are few common examples of infix notations in Kotlin –

1. Infix Notation Example – Creating a Map

val map = mapOf(1 to "one", 2 to "two", 3 to "three")

In the above example, the expressions 1 to "one"2 to "two" etc, are infix notations of the function calls"one") and"two") etc.

to() is an infix function that creates a Pair<A, B> from two values.

2. Infix Notation Example – Range Operators (until, downTo, step)

Kotlin provides various range operators that are usually called using infix notation –

for(i in 1 until 10) {	// Same as - for(i in 1.until(10))
    print("$i ")
for(i in 10 downTo 1) {	 // Same as - for(i in 10.downTo(1))
    print("$i ")
for(i in 1 until 10 step 2) { // Same as - for(i in 1.until(10).step(2))
    print("$i ")

3. Infix Notation Example – String.matches()

The String.matches() function in Kotlin which matches a String with a Regex is an infix function –

val regex = Regex("[tT]rue|[yY]es")
val str = "yes"


// Infix notation of the above function call -
str matches regex

Creating an Infix Function

You can make a single argument member function or extension function, an infix function by marking it with the infix keyword.

Check out the following example where I have created an infix member function called add() for adding two Complex numbers –

data class ComplexNumber(val realPart: Double, val imaginaryPart: Double) {
	// Infix function for adding two complex numbers
    infix fun add(c: ComplexNumber): ComplexNumber {
        return ComplexNumber(realPart + c.realPart, imaginaryPart + c.imaginaryPart)

You can now call the add() method using infix notation –

val c1 = ComplexNumber(3.0, 5.0)
val c2 = ComplexNumber(4.0, 7.0)

// Usual call
c1.add(c2) // produces - ComplexNumber(realPart=7.0, imaginaryPart=12.0)

// Infix call
c1 add c2  // produces - ComplexNumber(realPart=7.0, imaginaryPart=12.0)


That’s all folks. In this article, You learned what infix notation is and how it works. You saw several examples of Infix notations in Kotlin and also learned how to create an infix function.

Thanks for reading. Please ask any doubts in the comment section below.

Kotlin Control Flow: if and when expressions, for and while loops

Kotlin Control Flow: if and when expressions, for and while loops

n this article, You’ll learn how to use Kotlin’s control flow expressions and statements which includes conditional expressions like ifif-elsewhen and looping statements like forwhile, and do-while.

If Statement

The If statement allows you to specify a section of code that is executed only if a given condition is true-

var n = 34
if(n % 2 == 0) {
	println("$n is even")

// Displays - "34 is even"

The curly braces are optional if the body of if statement contains a single line –

if(n % 2 == 0) println("$n is even")

If-Else Statement

The if-else statement executes one section of code if the condition is true and the other if the condition is false –

var a = 32
var b = 55

if(a > b) {
    println("max($a, $b) = $a")
} else {
    println("max($a, $b) = $b")

// Displays - "max(32, 55) = 55"

Using If as an Expression

In Kotlin, You can use if as an expression instead of a statement. For example, you can assign the result of an if-else expression to a variable.

Let’s rewrite the if-else example of finding the maximum of two numbers that we saw in the previous section as an expression –

var a = 32
var b = 55

var max = if(a > b) a else b
println("max($a, $b) = $max")

// Displays - "max(32, 55) = 55"

Note that when you’re using if as an expression, it is required to have an else branch, otherwise, the compiler will throw an error.

The if-else branches can also have block bodies. In case of block bodies, the last expression is the value of the block –

var a = 32
var b = 55

var max = if(a > b) {
    println("$a is greater than $b")
} else {
    println("$a is less than or equal to $b")
println("max($a, $b) = $max")
# Output
32 is less than or equal to 55
max(32, 55) = 55

Unlike Java, Kotlin doesn’t have a ternary operator because we can easily achieve what ternary operator does, using an if-else expression.

If-Else-If Chain

You can chain multiple if-else-if blocks like this –

var age = 17
if(age < 12) {
} else if (age in 12..17) {
} else if (age in 18..21) {
    println("Young Adult")
} else if (age in 22..30) {
} else if (age in 30..50) {
    println("Middle Aged")
} else {

// Displays - "Teen"

In the next section, we’ll learn how to represent if-else-if chain using a when expression to make it more concise.

When Expression

Kotlin’s when expression is the replacement of switch statement from other languages like C, C++, and Java. It is concise and more powerful than switch statements.

Here is how a when expression looks like –

var dayOfWeek = 4
when(dayOfWeek) {
    1 -> println("Monday")
    2 -> println("Tuesday")
    3 -> println("Wednesday")
    4 -> println("Thursday")
    5 -> println("Friday")
    6 -> println("Saturday")
    7 -> println("Sunday")
    else -> println("Invalid Day")
// Displays - "Thursday"

when expression matches the supplied argument with all the branches one by one until a match is found. Once a match is found, it executes the matched branch. If none of the branches match, the else branch is executed.

In the above example, all the branches contain a single statement. But they can also contain multiple statements enclosed in a block –

var dayOfWeek = 1
when(dayOfWeek) {
    1 -> {
        // Block
        println("First day of the week")
    7 -> println("Sunday")
    else -> println("Other days")

Using when as an expression

Just like ifwhen can be used as an expression and we can assign its result to a variable like so –

var dayOfWeek = 4

var dayOfWeekInString = when(dayOfWeek) {
    1 -> "Monday"
    2 -> "Tuesday"
    3 -> "Wednesday"
    4 -> "Thursday"
    5 -> "Friday"
    6 -> "Saturday"
    7 -> "Sunday"
    else -> "Invalid Day"

println("Today is $dayOfWeekInString")	// Today is Thursday

Combining multiple when branches into one using comma

You can combine multiple branches into one using comma. This is helpful when you need to run a common logic for multiple cases –

var dayOfWeek = 6
when(dayOfWeek) {
    1, 2, 3, 4, 5 -> println("Weekday")
    6, 7 -> println("Weekend")
    else -> println("Invalid Day")
// Displays - Weekend

Checking whether a given value is in a range or not using in operator

range is created using the .. operator. For example, you can create a range from 1 to 10 using 1..10. You’ll learn more about range in a future article.

The in operator allows you to check if a value belongs to a range/collection –

var dayOfMonth = 5
when(dayOfMonth) {
    in 1..7 -> println("We're in the first Week of the Month")
    !in 15..21 -> println("We're not in the third week of the Month")
    else -> println("none of the above")
// Displays - We're in the first Week of the Month

Checking whether a given variable is of certain type or not using is operator

var x : Any = 6.86
when(x) {
    is Int -> println("$x is an Int")
    is String -> println("$x is a String")
    !is Double -> println("$x is not Double")
    else -> println("none of the above")
// Displays - none of the above

Using when as a replacement for an if-else-if chain

var number = 20
when {
    number < 0 -> println("$number is less than zero")
    number % 2 == 0 -> println("$number is even")
    number > 100 -> println("$number is greater than 100")
    else -> println("None of the above")
// Displays - 20 is even

While Loop

While loop executes a block of code repeatedly as long as a given condition is true –

while(condition) {
    // code to be executed

Here is an example –

var x = 1
while(x <= 5) {
    println("$x ")

// Displays - 1 2 3 4 5

In the above example, we increment the value of x by 1 in each iteration. When x reaches 6, the condition evaluates to false and the loop terminates.

do-while loop

The do-while loop is similar to while loop except that it tests the condition at the end of the loop.

var x = 1
do {
    print("$x ")
} while(x <= 5)

// Displays - 1 2 3 4 5

Since do-while loop tests the condition at the end of the loop. It is executed at least once –

var x = 6
do {
    print("$x ")
} while(x <= 5)

// Displays - 6

For Loop

A for-loop is used to iterate through ranges, arrays, collections, or anything that provides an iterator (You’ll learn about iterator in a future article).

Iterating through a range

for(value in 1..10) {
    print("$value ")
// Displays - 1 2 3 4 5 6 7 8 9 10

Iterating through an array

var primeNumbers = intArrayOf(2, 3, 5, 7, 11)

for(number in primeNumbers) {
    print("$number ")
// Displays - 2, 3, 5, 7, 11

Iterating through an array using its indices

Every array in Kotlin has a property called indices which returns a range of valid indices of that array.

You can iterate over the indices of the array and retrieve each array element using its index like so –

var primeNumbers = intArrayOf(2, 3, 5, 7, 11)

for(index in primeNumbers.indices) {
    println("PrimeNumber(${index+1}): ${primeNumbers[index]}")
# Output
PrimeNumber(1): 2
PrimeNumber(2): 3
PrimeNumber(3): 5
PrimeNumber(4): 7
PrimeNumber(5): 11

Iterating through an array using withIndex()

You can use the withIndex() function on arrays to obtain an iterable of IndexedValue type. This allows you to access both the index and the corresponding array element in each iteration –

var primeNumbers = intArrayOf(2, 3, 5, 7, 11)

for((index, number) in primeNumbers.withIndex()) {
    println("PrimeNumber(${index+1}): $number")

The output of this snippet is same as the previous snippet.

Break and Continue

Break out of a loop using the break keyword

for (num in 1..100) {
    if (num%3 == 0 && num%5 == 0) {
        println("First positive no divisible by both 3 and 5: ${num}")
# Output
First positive no divisible by both 3 and 5: 15

Skip to the next iteration of a loop using the continue keyword

for (num in 1..10) {
    if (num%2 == 0) {
    print("${num} ")
# Output
1 3 5 7 9 


That’s all folks! In this article, you learned how to use Kotlin’s conditional expressions like ifif-elsewhen, and looping statements like forwhile and do-while. You can find more articles from the sidebar menu.

Kotlin Variables and Data Types

Kotlin Variables and Data Types

In this article, You’ll learn how to declare variables in Kotlin, how Kotlin infers the type of variables, and what are the basic data types supported by Kotlin for creating variables.

You’ll also learn how to work with various data types and how to convert one type to another.


A variable refers to a memory location that stores some data. It has a name and an associated type. The type of a variable defines the range of values that the variable can hold, and the operations that can be done on those values.

You can declare a variable in Kotlin using var and val keywords.

A variable declared using val keyword is immutable (read-only). It cannot be reassigned after it is initialized –

val name = "Bill Gates"
name = "Satoshi Nakamoto"	// Error: Val cannot be reassigned 

For defining a mutable variable, i.e. a variable whose value can be changed, use the var keyword –

var country = "USA"
country = "India"    // Works

Type inference

Did you notice one thing about the variable declarations in the previous section? We didn’t specify the type of variables.

Although Kotlin is a statically typed language, It doesn’t require you to explicitly specify the type of every variable you declare. It can infer the type of a variable from the initializer expression –

val greeting = "Hello, World"  // type inferred as `String`
val year = 2018                // type inferred as `Int`

If you want to explicitly specify the type of a variable, you can do that like this –

// Explicitly defining the type of variables
val greeting: String = "Hello, World" 
val year: Int = 2018

Note that the type declaration becomes mandatory if you’re not initializing the variable at the time of declaration –

var language   // Error: The variable must either have a Type annotation or be initialized
language =  "French"

The above variable declaration fails because Kotlin has no way to infer the type of the variable without an initializer expression. In this case, you must explicitly specify the type of the variable –

var language: String   // Works
language = "French"

Data Types

Data Types are used to categorize a set of related values and define the operations that can be done on them.

Just like other languages, Kotlin has predefined types like IntDouble BooleanChar etc.

In Kotlin, everything (even the basic types like Int and Boolean) is an object. More specifically, everything behaves like an Object.

Kotlin may represent some of the basic types like numbers, characters and booleans as primitive values at runtime to improve performance, but for the end users, all of them are objects.

This is contrary to languages like Java that has separate primitive types like intdoubleetc, and their corresponding wrapper types like IntegerDouble etc.

Let’s now look at all the basic data types used in Kotlin one by one –


Numeric types in Kotlin are similar to Java. They can be categorized into integer and floating point types.


  • Byte – 8 bit
  • Short– 16 bit
  • Int – 32 bit
  • Long – 64 bit

Floating Point Numbers

  • Float – 32 bit single-precision floating point value.
  • Double – 64 bit double-precision floating point value.

Following are few examples of numeric types –

// Kotlin Numeric Types Examples
val myByte: Byte = 10
val myShort: Short = 125

val myInt = 1000
val myLong = 1000L	// The suffix 'L' is used to specify a long value

val myFloat = 126.78f   // The suffix 'f' or 'F' represents a Float 
val myDouble = 325.49

You can also use underscore in numeric values to make them more readable –

val hundredThousand = 100_000
val oneMillion = 1_000_000

You can declare hexadecimal and binary values like this –

val myHexa = 0x0A0F  // Hexadecimal values are prefixed with '0x' or '0X'
val myBinary = 0b1010  // Binary values are prefixed with '0b' or '0B'

Note that Kotlin doesn’t have any representation for octal values.


The type Boolean is used to represent logical values. It can have two possible values true and false.

val myBoolean = true
val anotherBoolean = false


Characters are represented using the type Char. Unlike Java, Char types cannot be treated as numbers. They are declared using single quotes like this –

val letterChar = 'A'
val digitChar = '9'

Just like other languages, special characters in Kotlin are escaped using a backslash. Some examples of escaped characters are – \n (newline), \t (tab), \r (carriage return), \b (backspace) etc.


Strings are represented using the String class. They are immutable, that means you cannot modify a String by changing some of its elements.

You can declare a String like this –

var myStr = "Hello, Kotlin"

You can access the character at a particular index in a String using str[index]. The index starts from zero –

var name = "John"
var firstCharInName = name[0]  // 'J'
var lastCharInName = name[name.length - 1]  // 'n'

The length property is used to get the length of a String.

Escaped String and Raw String

Strings declared in double quotes can have escaped characters like ‘\n’ (new line), ‘\t’ (tab) etc –

var myEscapedString = "Hello Reader,\nWelcome to my Blog"

In Kotlin, you also have an option to declare raw strings. These Strings have no escaping and can span multiple lines –

var myMultilineRawString = """
    The Quick Brown Fox
    Jumped Over a Lazy Dog.


Arrays in Kotlin are represented using the Array class. You can create an array in Kotlin either using the library function arrayOf() or using the Array() constructor.

Creating Arrays using the arrayOf library function

You can pass a bunch of values to the arrayOf function to create an array like this –

var numbers = arrayOf(1, 2, 3, 4, 5)
var animals = arrayOf("Cat", "Dog", "Lion", "Tiger")

Note that you can also pass values of mixed types to the arrayOf() function, and it will still work (but don’t do that) –

var mixedArray = arrayOf(1, true, 3, "Hello", 'A')	// Works and creates an array of Objects

You can also enforce a particular type while creating the array like this –

var numArray = arrayOf<Int>(1, 2, 3, 4, "Hello")  // Compiler Error

Accessing the elements of an array by their index

You can access the element at a particular index in an array using array[index]. The index starts from zero –

val myDoubleArray = arrayOf(4.0, 6.9, 1.7, 12.3, 5.4)
val firstElement = myDoubleArray[0]
val lastElement = myDoubleArray[myDoubleArray.size - 1]

Every array has a size property that you can use to get the size of the array.

You can also modify the array element at an index like this –

val a = arrayOf(4, 5, 7)  // [4, 5, 7]
a[1] = 10		          // [4, 10, 7]	

Primitive Arrays

As we learned earlier, everything in Kotlin is an object. But to improve performance it represents some of the basic types like numbers, characters and booleans as primitive types at runtime.

The arrayOf() function creates arrays of boxed/wrapper types. That is, arrayOf(1, 2, 3) corresponds to Java’s Integer[] array.

But, Kotlin provides a way to create arrays of primitive types as well. It contains specialized classes for representing array of primitive types. Those classes are – IntArrayDoubleArrayCharArray etc. You can create an array of primitive types using the corresponding library functions – intArrayOf()doubleArrayOf()charArrayOf() etc. –

val myCharArray = charArrayOf('K', 'O', 'T')  // CharArray (corresponds to Java 'char[]')
val myIntArray = intArrayOf(1, 3, 5, 7)		// IntArray (corresponds to Java 'int[]')

Creating Arrays using the Array() constructor

The Array() constructor takes two arguments –

  1. the size of the array, and
  2. a function that takes the array index as an argument and returns the element to be inserted at that index.
var mySquareArray = Array(5, {i -> i * i})	// [0, 1, 4, 9, 16]

The second argument to the Array() constructor is a lambda expression. Lambda expressions are anonymous functions that are declared and passed around as expressions. We’ll learn more about lambda expressions in a future tutorial.

The above lambda expression takes the index of an array element and returns the value that should be inserted at that index, which is the square of the index in this case.

Type Conversions

Unlike Java, Kotlin doesn’t support implicit conversion from smaller types to larger types. For example, Int cannot be assigned to Long or Double.

var myInt = 100
var myLong: Long = myInt // Compiler Error

However, Every number type contains helper functions that can be used to explicitly convert one type to another.

Following helper functions are supported for type conversion between numeric types –

  • toByte()
  • toShort()
  • toInt()
  • toLong()
  • toFLoat()
  • toDouble()
  • toChar()

Examples of explicit type conversions

Here is how you can convert an Int to Long –

val myInt = 100
val myLong = myInt.toLong()   // Explicitly converting 'Int' to 'Long'

You can also convert larger types to smaller types –

val doubleValue = 176.80
val intValue = doubleValue.toInt()  // 176

Every type in Kotlin, not just numeric type, supports a helper function called toString() to convert it to String.

val myInt = 1000
myInt.toString()  // "1000"

You can also convert a String to a numeric type like so –

val str = "1000"
val intValue = str.toInt()

If the String-to-Number conversion is not possible then a NumberFormatException is thrown –

val str = "1000ABC"
str.toInt()   // Throws java.lang.NumberFormatException


That’s all folks! In this article, You learned how to declare mutable and immutable variables. How type inference works in Kotlin. What are the basic data types supported in Kotlin. How to work with data types like IntLong DoubleCharBooleanString and Array, and how to convert one type to another.

Nullable Types and Null Safety in Kotlin

Nullable Types and Null Safety in Kotlin

if you have been programming in Java or any other language that has the concept of null reference then you must have heard about or experienced NullPointerException in your programs.

NullPointerExceptions are Runtime Exceptions which are thrown by the program at runtime causing application failure and system crashes.

Wouldn’t it be nice if we could detect possible NullPointerException exception errors at compile time itself and guard against them?

Well, Enter Kotlin!

Nullability and Nullable Types in Kotlin

Kotlin supports nullability as part of its type System. That means You have the ability to declare whether a variable can hold a null value or not.

By supporting nullability in the type system, the compiler can detect possible NullPointerException errors at compile time and reduce the possibility of having them thrown at runtime.

Let’s understand how it works!

All variables in Kotlin are non-nullable by default. So If you try to assign a null value to a regular variable, the compiler will throw an error –

var greeting: String = "Hello, World"
greeting = null // Compilation Error

To allow null values, you have to declare a variable as nullable by appending a question mark in its type declaration –

var nullableGreeting: String? = "Hello, World"
nullableGreeting = null // Works

We know that NullPointerException occurs when we try to call a method or access a property on a variable which is null. Kotlin disallows method calls and property access on nullable variables and thereby prevents many possible NullPointerExceptions.

For example, The following method access works because Kotlin knows that the variable greeting can never be null –

val len = greeting.length 
val upper = greeting.toUpperCase() 

But the same method call won’t work with nullableGreeting variable –

val len = nullableGreeting.length // Compilation Error
val upper = nullableGreeting.toUpperCase()  // Compilation Error

Since Kotlin knows beforehand which variable can be null and which cannot, It can detect and disallow calls which could result in NullPointerException at compile-time itself.

Working with Nullable Types

All right, It’s nice that Kotlin disallows method calls and property access on nullable variables to guard against NullPointerException errors. But we still need to do that right?

Well, There are several ways of safely doing that in Kotlin.

1. Adding a null Check

The most trivial way to work with nullable variables is to perform a null check before accessing a property or calling a method on them –

val nullableName: String? = "John"

if(nullableName != null) {
    println("Hello, ${nullableName.toUpperCase()}.")
    println("Your name is ${nullableName.length} characters long.")
} else {
    println("Hello, Guest")

Once you perform a null comparison, the compiler remembers that and allows calls to toUpperCase() and length inside the if branch.

2. Safe call operator: ?.

Null Comparisons are simple but too verbose. Kotlin provides a Safe call operator, ?. that reduces this verbosity. It allows you to combine a null-check and a method call in a single expression.

For example, The following expression –


is same as –

if(nullableName != null) 

Wow! That saves a lot of keystrokes, right? 🙂

So if you were to print the name in uppercase and its length safely, you could do the following –

val nullableName: String? = null

// Prints 

That printed null since the variable nullableName is null, otherwise, it would have printed the name in uppercase and its length.

But what if you don’t want to print anything if the variable is null?

Well, To perform an operation only if the variable is not null, you can use the safe call operator with let –

val nullableName: String? = null

nullableName?.let { println(it.toUpperCase()) }
nullableName?.let { println(it.length) }

// Prints nothing

The lambda expression inside let is executed only if the variable nullableName is not null.

That’s great but that’s not all. Safe call operator is even more powerful than you think. For example, You can chain multiple safe calls like this –

val currentCity: String? = user?.address?.city

The variable currentCity will be null if any of useraddress or city is null. (Imagine doing that using null-checks.)

3. Elvis operator: ?:

The Elvis operator is used to provide a default value when the original variable is null –

val name = nullableName ?: "Guest"

The above expression is same as –

val name = if(nullableName != null) nullableName else "Guest"

In other words, The Elvis operator takes two values and returns the first value if it is not null, otherwise, it returns the second value.

The Elvis operator is often used with Safe call operator to provide a default value other than null when the variable on which a method or property is called is null –

val len = nullableName?.length ?: -1

You can have more complex expressions on the left side of Elvis operator –

val currentCity = user?.address?.city ?: "Unknown"

Moreover, You can use throw and return expressions on the right side of Elvis operator. This is very useful while checking preconditions in a function. So instead of providing a default value in the right side of Elvis operator, you can throw an exception like this –

val name = nullableName ?: throw IllegalArgumentException("Name can not be null")

4. Not null assertion : !! Operator

The !! operator converts a nullable type to a non-null type, and throws a NullPointerException if the nullable type holds a null value.

So It’s a way of asking for NullPointerException explicitly. Please don’t use this operator.

val nullableName: String? = null
nullableName!!.toUpperCase() // Results in NullPointerException

Null Safety and Java Interoperability

Kotlin is fully interoperable with Java but Java doesn’t support nullability in its type system. So what happens when you call Java code from Kotlin?

Well, Java types are treated specially in Kotlin. They are called Platform types. Since Kotlin doesn’t have any information about the nullability of a type declared in Java, It relaxes compile-time null checks for these types.

So you don’t get any null safety guarantee for types declared in Java, and you have full responsibility for operations you perform on these types. The compiler will allow all operations. If you know that the Java variable can be null, you should compare it with null before use, otherwise, just like Java, you’ll get a NullPointerException at runtime if the value is null.

Consider the following User class declared in Java –

public class User {
    private final String name;

    public User(String name) { = name;

    public String getName() {
        return name;

Since Kotlin doesn’t know about the nullability of the member variable name, It allows all operations on this variable. You can treat it as nullable or non-nullable, but the compiler won’t enforce anything.

In the following example, We simply treat the variable name as non-nullable and call methods and properties on it –

val javaUser = User(null)

println( // Allowed (Throws NullPointerException)
println( // Allowed (Throws NullPointerException)

The other option is to treat the member variable name as nullable and use the safe operator for calling methods or accessing properties –

val javaUser = User(null)

println( // Allowed (Prints null)
println( // Allowed (Prints null)

Nullability Annotations

Although Java doesn’t support nullability in its type system, You can use annotations like @Nullable and @NotNull provided by external packages like javax.validation.constraintsorg.jetbrains.annotations etc to mark a variable as Nullable or Not-null.

Java compiler doesn’t use these annotations, but these annotations are used by IDEs, ORM libraries and other external tools to provide assistance while working with null values.

Kotlin also respects these annotations when they are present in Java code. Java types which have these nullability annotations are represented as actual nullable or non-null Kotlin types instead of platform types.

Nullability and Collections

Kotlin’s collection API is built on top of Java’s collection API but it fully supports nullability on Collections.

Just as regular variables are non-null by default, a normal collection also can’t hold null values –

val regularList: List<Int> = listOf(1, 2, null, 3) // Compiler Error

1. Collection of Nullable Types

Here is how you can declare a Collection of Nullable Types in Kotlin –

val listOfNullableTypes: List<Int?> = listOf(1, 2, null, 3) // Works

To filter non-null values from a list of nullable types, you can use the filterNotNull() function –

val notNullList: List<Int> = listOfNullableTypes.filterNotNull()

2. Nullable Collection

Note that there is a difference between a collection of nullable types and a nullable collection.

A collection of nullable types can hold null values but the collection itself cannot be null –

var listOfNullableTypes: List<Int?> = listOf(1, 2, null, 3) // Works
listOfNullableTypes = null // Compilation Error

You can declare a nullable collection like this –

var nullableList: List<Int>? = listOf(1, 2, 3)
nullableList = null // Works

3. Nullable Collection of Nullable Types

Finally, you can declare a nullable collection of nullable types like this –

var nullableListOfNullableTypes: List<Int?>? = listOf(1, 2, null, 3) // Works
nullableListOfNullableTypes = null // Works


That’s all in this article folks. I hope you understood how kotlin helps you avoid NullPointerException errors with its nullable type concept.

Thanks for reading. See you in the next post.

Writing your first Kotlin program

Writing your first Kotlin program

The first program that we typically write in any programming language is the “Hello, World” program. Let’s write the “Hello, World” program in Kotlin and understand its internals.

The “Hello, World!” program in Kotlin

Open your favorite editor or an IDE and create a file named hello.kt with the following code –

// Kotlin Hello World Program
fun main(args: Array<String>) {
    println("Hello, World!")

You can compile and run the program using Kotlin’s compiler like so –

$ kotlinc hello.kt
$ kotlin HelloKt
Hello, World!

You can also run the program in an IDE like Eclipse or IntelliJ. Learn how to Setup and run Kotlin programs in your system.

Internals of the “Hello, World!” program

  • Line 1. The first line is a comment. Comments are ignored by the compiler. They are used for your own sake (and for others who read your code).Kotlin supports two different styles of comments similar to other languages like C, C++, and Java –
    1. Single Line Comment:// This is a Single line comment
    2. Multi-line Comment:/* This is an example of a multi-line comment. It can span over multiple lines. */
  • Line 2. The second line defines a function called main(args: Array<String>) { // ... } Functions are the building blocks of a Kotlin program. All functions in Kotlin start with the keyword fun followed by a name of the function (main in this case), a list of zero or more comma-separated parameters, an optional return type, and a body.The main() function takes one argument – an Array of strings, and returns Unit. The Unit type corresponds to void in Java. It is used to indicate that the function doesn’t return any meaningful value.The Unit type is optional. i.e. you don’t need to declare it explicitly in the function declaration –fun main(args: Array<String>): Unit { // `Unit` is optional } If you don’t specify a return type, Unit is assumed.The main() function is not just any ordinary function. It is the entry point of your program. It is the first thing that gets called when you run a Kotlin program.
  • Line 3. The third line is a statement. It prints a String “Hello, World!” to standard output.println("Hello, World!") // No Semicolons needed :) Note that we can directly use println() to print to standard output, unlike Java where we need to use System.out.println().Kotlin provides several wrappers over standard Java library functions, println is one of them.Also, Semicolons are optional in Kotlin, just like many other modern languages.


Congratulations! You just wrote your first program in Kotlin. You learned about the main method, single-line and multi-line comments, and the println library function.

In the next article, you’ll learn how to create variables in Kotlin and also look at various data types that are supported for creating variables.

Building Restful APIs with Kotlin, Spring Boot, Mysql, JPA and Hibernate

Building Restful APIs with Kotlin, Spring Boot, MySQL , JPA and Hibernate

Kotlin has gained a lot of popularity in recent times due to its productivity features and a first class support in Android.

Owing to the increasing popularity of Kotlin, Spring framework 5 has also introduced a dedicated support for Kotlin in Spring applications.

In this article, You’ll learn how to build a Restful CRUD API with Kotlin and Spring Boot 2.x, which is based on Spring framework 5.

So Stay tuned!

What will we build?

In this blog post, we’ll build Restful APIs for a mini blog application. The blog has a list of Articles. We’ll write APIs for creating, retrieving, updating and deleting an Article. An Article has an id, a title and some content.

We’ll use MySQL as our data source and JPA & Hibernate to access the data from the database.

All right, Let’s now create the application.

Creating the Application

We’ll use Spring initializr web tool to bootstrap our application. Follow the steps below to generate the application :

  1. Go to
  2. Select Kotlin in the language section.
  3. Enter Artifact as kotlin-demo
  4. Add WebJPA, and MySQL dependencies.
  5. Click Generate to generate and download the project.
Kotlin Spring Boot Restful CRUD API Example

Once the project is generated, unzip it and import it into your favorite IDE. Here is the Project’s directory Structure for your reference.

Kotlin Spring Boot Restful CRUD API Example Directory Structure

Configure MySQL

We’ll need to configure MySQL database url, username, and password so that Spring Boot can create a Data source.

Open src/main/resources/ file and add the following properties to it –

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/kotlin_demo_app?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false
spring.datasource.username = root
spring.datasource.password = root

## Hibernate Properties

# The SQL dialect makes Hibernate generate better SQL for the chosen database = org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

Please don’t forget to change spring.datasource.username and spring.datasource.password as per your MySQL installation.

Note that, I’ve set spring.jpa.hibernate.ddl-auto property to update. This property updates the database schema whenever you create or modify the domain models in your application.

Creating the Domain Model

Let’s now create the Article domain entity. Create a new package called model inside com.example.kotlindemo package, and then create a new Kotlin file called Article.kt with the following contents –

package com.example.kotlindemo.model

import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.validation.constraints.NotBlank

data class Article (
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0,

    @get: NotBlank
    val title: String = "",

    @get: NotBlank
    val content: String = ""

The Entity class is so small and concise, right? That’s because A Kotlin class doesn’t need getters and setters like Java. Moreover, I have used a data class here. A data class automatically generates equals()hashcode()toString() and copy() methods.

Note that, I’ve assigned a default value for all the fields in the Article class. This is needed because Hibernate requires an entity to have a no-arg constructor.

Assigning default values to all the member fields will let hibernate instantiate an Article without passing any argument. It Works because Kotlin supports Default Arguments 🙂

Creating the Repository

Let’s now create the repository for accessing the data from the database. First, create a package called repository inside com.example.kotlindemo package, and then create a Kotlin file named ArticleRepository.kt with the following contents –

package com.example.kotlindemo.repository

import com.example.kotlindemo.model.Article
import org.springframework.stereotype.Repository

interface ArticleRepository : JpaRepository<Article, Long>

That’s all we need to do here. Since we’ve extended ArticleRepository from JpaRepository interface, all the CRUD methods on Article entity is readily available to us. Spring boot automatically plugs-in a default implementation of JpaRepository called SimpleJpaRepository at runtime.

Creating the controller End-points

Finally, Let’s create the controller end-points for all the CRUD operations on Article entity.

First, create a new package called controller inside com.example.kotlindemo package and then create a new kotlin file called ArticleController.kt inside controller package with the following contents –

package com.example.kotlindemo.controller

import com.example.kotlindemo.model.Article
import com.example.kotlindemo.repository.ArticleRepository
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import java.util.*
import javax.validation.Valid

class ArticleController(private val articleRepository: ArticleRepository) {

    fun getAllArticles(): List<Article> =

    fun createNewArticle(@Valid @RequestBody article: Article): Article =

    fun getArticleById(@PathVariable(value = "id") articleId: Long): ResponseEntity<Article> {
        return articleRepository.findById(articleId).map { article -> 

    fun updateArticleById(@PathVariable(value = "id") articleId: Long,
                          @Valid @RequestBody newArticle: Article): ResponseEntity<Article> {

        return articleRepository.findById(articleId).map { existingArticle ->
            val updatedArticle: Article = existingArticle
                    .copy(title = newArticle.title, content = newArticle.content)


    fun deleteArticleById(@PathVariable(value = "id") articleId: Long): ResponseEntity<Void> {

        return articleRepository.findById(articleId).map { article  ->


The controller defines APIs for all the CRUD operations. I have used Kotlin’s functional style syntax in all the methods to make them short and concise.

Running the Application

You can run the application by typing the following command in the terminal –

mvn spring-boot:run

The application will start at Spring Boot’s default port 8080.

Exploring the Rest APIs

1. POST /api/articles – Create an Article

curl -i -H "Content-Type: application/json" -X POST \
-d '{"title": "How to learn Spring framework", "content": "Resources to learn Spring framework"}' \

# Output
HTTP/1.1 200 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 06 Oct 2017 03:25:59 GMT

{"id":1,"title":"How to learn Spring framework","content":"Resources to learn Spring framework"}

2. GET /api/articles – Get all Articles

curl -i -H 'Accept: application/json' http://localhost:8080/api/articles

# Output
HTTP/1.1 200 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 06 Oct 2017 03:25:29 GMT

[{"id":1,"title":"How to learn Spring framework","content":"Resources to learn Spring framework"}]

3. Get /api/articles/{id} – Get an Article by id

curl -i -H 'Accept: application/json' http://localhost:8080/api/articles/1

# Output
HTTP/1.1 200 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 06 Oct 2017 03:27:51 GMT

{"id":1,"title":"How to learn Spring framework","content":"Resources to learn Spring framework"}

4. PUT /api/articles/{id} – Update an Article

curl -i -H "Content-Type: application/json" -X PUT \
-d '{"title": "Learning Spring Boot", "content": "Some resources to learn Spring Boot"}' \

# Output
HTTP/1.1 200 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 06 Oct 2017 03:33:15 GMT

{"id":1,"title":"Learning Spring Boot","content":"Some resources to learn Spring Boot"}

5. DELETE /api/articles/{id} – Delete an Article

curl -i -X DELETE http://localhost:8080/api/articles/1

# Output
HTTP/1.1 200 
Content-Length: 0
Date: Fri, 06 Oct 2017 03:34:22 GMT


That’s all folks! In this article, You learned how to use Kotlin with Spring Boot for building restful web services.

You can find the entire code for the application that we built in this article in my github repository. Consider giving a star on github if you find the project useful.

Thank you for reading folks! See you next time 🙂

Kotlin Overview, Installation, and Setup

Kotlin Overview, Installation, and Setup

Kotlin is a programming language developed by JetBrains, the same company that has built world-class IDEs like IntelliJ IDEA, PhpStorm, PyCharm, ReSharper etc.

It runs on the Java Virtual Machine (JVM), and can also be compiled to JavaScript and Machine Code.

In this tutorial, I’ll give you a brief overview of Kotlin and its features. I’ll also help you set up Kotlin in your system and prepare you for future tutorials.

Why Kotlin?

In today’s world where we have a dozen programming language for every possible task, following are few reasons to choose Kotlin as the primary language for your next exciting project –

1. Statically Typed

Kotlin is a Statically typed programming language. This means that the type of every variable and expression is known at compile time.

The advantage with static typing is that the compiler can validate the methods calls and property access on the objects at compile time itself and prevent lots of trivial bugs that would otherwise crop up at runtime.

Although Kotlin is a statically typed language, it doesn’t require you to explicitly specify the type of every variable you declare. Most of the time, Kotlin can infer the type of a variable from the initializer expression or the surrounding context. This is called Type Inference. You’ll learn more about Type inference in the Variables and Data Types tutorial.

2. Concise

Kotlin is concise. It drastically reduces the amount of boilerplate code that you have been writing all the time in other OOP languages like Java.

It provides rich idioms for performing common tasks. For example, You can create a POJO class with getters, setters, equals()hashCode() and toString() methods in a single line –

data class User(val name: String, val email: String, val country: String)

3. Safe

Kotlin is safe. It avoids the most dreaded and annoying NullPointerExceptions by supporting nullability as part of its type system.

It works like this – Every variable in Kotlin is non-null by default:

String str = "Hello, World"    // Non-null type (can't hold null value)
str = null // Compiler Error

To allow a variable to hold null value, you need to explicitly declare it as nullable:

String nullableStr? = null   // Nullable type (can be null)

Since Kotlin knows which variables are nullable and which are not, It can detect and disallow unsafe calls at compile time itself that would otherwise result in a NullPointerException at runtime –

println(nullableStr.length()) // Compiler Error

Kotlin doesn’t allow the method call length() on the nullableStr variable because the call is not safe and may lead to NullPointerException.

However, if you add a null check then the method call is allowed –

if(nullablStr != null) {

Notice how Kotlin is enforcing developers to write safe code by distinguishing between nullable and non-null types.

4. Explicit

Kotlin is Explicit. It will do/allow things only if you tell it to do so. Explicitness is considered a good thing. Being explicit means being specific about your design choices and not hiding anything from the readers or consumers of your code.

Following are few examples of Explicitness in Kotlin –

  • Kotlin doesn’t allow implicit type conversions, for example, int to long, or float to double. It provides methods like toLong() and toDouble() to do so explicitly.
  • All the classes in Kotlin are final (non-inheritable) by default. You need to explicitly mark a class as open to allow other classes to inherit from it. Similarly, All the properties and member functions of a class are final by default. You need to explicitly mark a function or property as open to allow child classes to override it.
  • If you’re overriding a parent class function or property, then you need to explicitly annotate it with the override modifier.

5. Easy to learn.

Kotlin has a very low learning curve. The basic syntax looks a lot like Java. If you have a little experience in Java or any other OOP language then you’ll be able to pick up Kotlin in a matter of hours.

6. Functional and Object Oriented Capabilities

Kotlin has both functional and object-oriented capabilities. It has a rich set of features to support functional programming which includes functional types, lambda expressions, data classes and much more.

7. Completely interoperable with Java

Kotlin is 100% interoperable with Java. You can easily access Java code from Kotlin and vice versa. You can use Kotlin and Java in the same project without any problem. This enables easy adoption of Kotlin into your existing Java projects.

Kotlin Java Interoperability

8. Excellent Tooling

Kotlin has excellent tooling support. You can choose any Java IDE – IntelliJ IDEA, Eclipse, Android Studio. All of them support Kotlin.

Moreover, you can also download Kotlin’s standalone compiler and run Kotlin code from the command line.

Kotlin Tool Friendly

9. Build Applications for Server Side, Android, Browser, and Desktop

You can use Koltin to build applications for a wide range of platforms including Server side, Android, Browser, and Desktop.

  • Android has official support for Kotlin.
  • On the server side, you can use Kotlin with the Spring framework which has added full support for Kotlin in Spring version 5.
  • Kotlin can be compiled to JavaScript and Machine code as well.

10. Free and Open Source

Kotlin programming language, including the compiler, libraries and all the tooling is completely free and open source. It is available under Apache 2 license and the complete project is hosted on Github –

Setup Kotlin

You can set up and run Kotlin programs in several ways. You can either install kotlin’s compiler and run Kotlin programs from the command line or install and setup Kotlin in an IDE like IntelliJ or Eclipse –

  • Install Kotlin’s Standalone Compiler
  • Setup Kotlin in IntelliJ IDEA
  • Setup Kotlin in Eclipse

Installing the Standalone Compiler

Follow the steps below to install Kotlin’s compiler –

  1. Go to Kotlin releases page on Github
  2. Download Kotlin’s compiler in the form of a zip file from the Assets section on the Github releases page. The latest version of Kotlin compiler at the time of writing this page is 1.2.10
  3. Unzip the downloaded file and store the unzipped folder in a location where you have write access.
  4. Add path-to-unzipped-folder/bin to your PATH variable.
  5. Verify the installation by typing kotlinc in the command line –
$ kotlinc
Welcome to Kotlin version 1.2.10 (JRE 1.8.0_112-b16)
Type :help for help, :quit for quit

Run your first Kotlin program from the command line

Open your favorite editor and create a new file called hello.kt with the following contents –

fun main(args: Array<String>) {
    println("Hello, World!")

Save the file and type the following commands to compile and run the program

$ kotlinc hello.kt
$ kotlin HelloKt
Hello, World

Setting up Kotlin in IntelliJ IDEA

Install the latest version of IntelliJ IDEA. Kotlin comes bundled with the recent versions of IntelliJ. You won’t need to install any plug-in separately to run Kotlin programs.

Follow these steps to create and run a new Kotlin project in IntelliJ

  1. Create a new project by selecting “Create New Project” on the welcome screen or go to File → New → Project.Select Kotlin on the left side menu and Kotlin/JVM from the options on the right side –IntelliJ Kotlin Project Setup
  2. Specify the project’s name and location, and select a Java version (1.6+) in the Project SDK. Once all the details are entered, click Finish to create the project –IntelliJ Kotlin Hello World Project ExampleThe generated project will look like this –IntelliJ Kotlin Hello World Project Directory Structure
  3. Let’s now create a new Kotlin file. Right click on src folder → New → Kotlin File/Class.IntelliJ Create new Kotlin ClassA prompt will appear where you’ll need to provide a name for the file. Let’s name it HelloWorld.
  4. Now let’s write a simple hello world program in the new file that we have created. Add the following main() function to the HelloWorld.kt file –Kotlin Hello World Example
  5. Finally, You can run the program by clicking the Kotlin icon that appears beside the main() method –Run Kotlin Program in IntelliJ IDEA

You can also run the program by Right Clicking the HelloWorld.kt file and selecting Run 'HelloWorldKt'.

Setting up Kotlin in Eclipse

I assume that you have Eclipse installed on your system. If not, download the eclipse installer from Eclipse Downloads page, and install “Eclipse IDE for Java Developers”.

Once Eclipse is installed, follow the steps below to setup and run Kotlin in Eclipse –

  1. Install Kotlin Plugin from Eclipse Marketplace: Go to Help → Eclipse Marketplace, and search for Kotlin.Eclipse Kotlin PluginClick install to install the plugin.
  2. You will need to restart eclipse once the installation is finished.
  3. Let’s verify the plugin’s installation switching to Kotlin perspective in eclipse. Go to Window → Perspective → Open Perspective → Other. A window will open which will show Kotlin as a new perspective. Select Kotlin and click Open to open Kotlin perspective –Eclipse Kotlin Perspective
  4. Let’s now create a new project. Select File → New → Kotlin Project. Enter the project’s name and click finish –Create Kotlin Project in Eclipse
  5. A new project will be created which will look like this –Eclipse Kotlin Project Directory Structure
  6. Let’s now create a new Kotlin file under the src folder. Right click src folder → New → Kotlin File –Create Kotlin File/Class in Eclipse
  7. First, add the following code in the HelloWorld.kt file, and then right-click anywhere on the source file and click Run As → Kotlin Application to run the application –Run Kotlin Application in Eclipse


That’s all folks! In this article, you learned about Kotlin and some of its features. You also learned how to setup and run Kotlin programs in your system using Kotlin’s standalone compiler and IDEs like IntelliJ and Eclipse.

Kotlin Inheritance, Method Overriding, and Property Overriding

Kotlin Inheritance, Method Overriding, and Property Overriding

Inheritance is one of the key concepts of Object Oriented Programming (OOP). Inheritance enables re-usability. It allows a class to inherit features (properties and methods) from another class.

The class that inherits the features of another class is called the Child class or Derived class or Sub class, and the class whose features are inherited is called the Parent class or Base class or Super class.

All the classes in Kotlin have a common base class called Any. It corresponds to the Object class in Java. Every class that you create in Kotlin implicitly inherits from Any –

class Person // Implicitly inherits from the default Super class - Any

The Any class contains three methods namely equals()hashCode() and toString(). All the classes in Kotlin inherit these three methods from Any, and can override them to provide their own implementation.

Inheritance (Creating Base and Derived classes)

Here is how you declare a base class and a derived class in Kotlin –

// Base class (Super class)
open class Computer {

// Derived class (Sub class)
class Laptop: Computer() {

Notice the use of open keyword in the base class. By default, all the classes in Kotlin are final (non-inheritable).

To allow a class to be inherited by others, you must mark it with the open modifier.

Note that the child class has the responsibility to initialize the parent class. If the child class has a primary constructor, then it must initialize the parent class right in the class header with the parameters passed to its primary constructor –

// Parent class
open class Computer(val name: String,
                    val brand: String) {

// Child class (initializes the parent class)
class Laptop(name: String, 
             brand: String, 
             val batteryLife: Double) : Computer(name, brand) {

If the child class doesn’t have a primary constructor, then all of its secondary constructors have to initialize the parent class either by calling the super keyword directly or by delegating to another constructor that does that –

class Laptop : Computer {
    val batteryLife: Double

	// Calls super() to initialize the Parent class
    constructor(name: String, brand: String, batteryLife: Double): super(name, brand) {
        this.batteryLife = batteryLife

	// Calls another constructor (which calls super())
    constructor(name: String, brand: String): this(name, brand, 0.0) {

In the above examples, we initialized the parent class using its primary constructor. If the parent class contains one or more secondary constructors, then the child class can initialize the parent class using any of the primary constructor or secondary constructors.

Just keep in mind that the parent class needs to be initialized. It doesn’t matter which of its constructor is used to initialize it.

Inheritance Example with Properties and Member Functions

Let’s now see a complete example of Inheritance in Kotlin. Consider a banking application where people can have several types of Bank accounts like SavingsAccount, CurrentAccount etc.

In such cases, it makes sense to create a base class called BankAccount and let other classes like SavingsAccount and CurrentAccount inherit from the BankAccount class.

Following is a simple BankAccount class for our Banking application –

 * BankAccount (Base Class)
 * @property accountNumber - Account Number (read-only)
 * @property accountName -  Account Name (read-only)
 * @property balance - Current Balance (Mutable)

open class BankAccount(val accountNumber: String, val accountName: String) {
    var balance : Double = 0.0

    fun depositeMoney(amount: Double): Boolean {
        if(amount > 0) {
            balance += amount
            return true
        } else {
            return false

    fun withdrawMoney(amount: Double): Boolean {
        if(amount > balance) {
            return false
        } else {
            balance -= amount
            return true


A Savings account is a Bank account with some interest rate on the balance amount. We can model the SavingsAccount class in the following way –

 * SavingsAccount (Derived Class)
 * @property interestRate - Interest Rate for SavingsAccount (read-only)
 * @constructor - Primary constructor for creating a Savings Account
 * @param accountNumber - Account Number (used to initialize BankAccount)
 * @param accountName - Account Name (used to initialize BankAccount)

class SavingsAccount (accountNumber: String, accountName: String, val interestRate: Double) :
        BankAccount(accountNumber, accountName) {

    fun depositInterest() {
        val interest = balance * interestRate / 100

The SavingsAccount class inherits the following features from the base class –

  • Properties – accountNumberaccountNamebalance
  • Methods – depositMoneywithdrawMoney

Let’s now write some code to test the above classes and methods –

fun main(args: Array<String>) {
    // Create a Savings Account with 6% interest rate
    val savingsAccount = SavingsAccount("64524627", "Rajeev Kumar Singh", 6.0)
    println("Current Balance = ${savingsAccount.balance}")

Overriding Member Functions

Just like Kotlin classes, members of a Kotlin class are also final by default. To allow a member function to be overridden, you need to mark it with the open modifier.

Moreover, The derived class that overrides a base class function must use the override modifier, otherwise, the compiler will generate an error –

open class Teacher {
    // Must use "open" modifier to allow child classes to override it
    open fun teach() {

class MathsTeacher : Teacher() {
    // Must use "override" modifier to override a base class function
    override fun teach() {
        println("Teaching Maths...")

Let’s test the above classes by defining the main method –

fun main(args: Array<String>) {
    val teacher = Teacher()
    val mathsTeacher = MathsTeacher()

    teacher.teach()  // Teaching...
    mathsTeacher.teach() // Teaching Maths..

Dynamic Polymorphism

Polymorphism is an important concept in Object Oriented Programming. There are two types of polymorphism –

  1. Static (compile-time) Polymorphism
  2. Dynamic (run-time) Polymorphism

Static polymorphism occurs when you define multiple overloaded functions with same name but different signatures. It is called compile-time polymorphism because the compiler can decide which function to call at compile itself.

Dynamic polymorphism occurs in case of function overriding. In this case, the function that is called is decided at run-time.

Here is an example –

fun main(args: Array<String>) {
    val teacher1: Teacher = Teacher()  // Teacher reference and object
    val teacher2: Teacher = MathsTeacher() // Teacher reference but MathsTeacher object

    teacher1.teach()  // Teaching...
    teacher2.teach() // Teaching Maths..

The line teacher2.teach() calls teach() function of MathsTeacher class even if teacher2 is of type Teacher. This is because teacher2 refers to a MathsTeacher object.

Overriding Properties

Just like functions, you can override the properties of a super class as well. To allow child classes to override a property of a parent class, you must annotate it with the open modifier.

Moreover, The child class must use override keyword for overriding a property of a parent class –

open class Employee {
    // Use "open" modifier to allow child classes to override this property
    open val baseSalary: Double = 30000.0

class Programmer : Employee() {
    // Use "override" modifier to override the property of base class
    override val baseSalary: Double = 50000.0

fun main(args: Array<String>) {
    val employee = Employee()
    println(employee.baseSalary) // 30000.0

    val programmer = Programmer()
    println(programmer.baseSalary) // 50000.0

Overriding Property’s Getter/Setter method

You can override a super class property either using an initializer or using a custom getter/setter.

In the example below, we’re overriding the age property by defining a custom setter method –

open class Person {
    open var age: Int = 1

class CheckedPerson: Person() {
    override var age: Int = 1
        set(value) {
            field = if(value > 0) value else throw IllegalArgumentException("Age can not be negative")

fun main(args: Array<String>) {
    val person = Person()
    person.age = -5 // Works

    val checkedPerson = CheckedPerson()
    checkedPerson.age = -5  // Throws IllegalArgumentException : Age can not be negative

Calling properties and functions of Super class

When you override a property or a member function of a super class, the super class implementation is shadowed by the child class implementation.

You can access the properties and functions of the super class using super() keyword.

Here is an example –

open class Employee {
    open val baseSalary: Double = 10000.0

    open fun displayDetails() {
        println("I am an Employee")

class Developer: Employee() {
    override var baseSalary: Double = super.baseSalary + 10000.0

    override fun displayDetails() {
        println("I am a Developer")


That’s all in this article folks. I hope you understood how inheritance works in Kotlin