Learn Kotlin

Learn Kotlin Step By Step Fast and Free

Table of Contents

Share and Enjoy !

Why learn kotlin? Humm let me answer that quickly. I am sure most of us out here are Android users right but have you ever wondered about the official programming language of Android well I’m talking about Kotlin. Many companies like Google Pinterest uber and other technology-driven companies go about using Kotlin for their daily needs and in this post, we check out a quick introduction to Kotlin and go about seeing what it offers to us as developers.

Introduction to Kotlin

Let’s touch on a few important goals of these tutorials before we get started. For instance, books will skip programming style sections, common pitfalls, debugging, good /bad programming practices and debugging. This tutorial covers best programming practice exercises and programs for you to learn and understand easily.

  • This Blog Tutorial consists of a lot of daily life example programs for the understanding of concepts, which helps learners to understand in a very effective and better way.
  • Provide practice programs at the end of tutorial documents.

Basics

  • What is Kotlin
  • Think But Why?
  • Installation of Git
  • Installation of Compiler/IntelliJ idea
  • How java resides with kotlin?
  • If statement in Kotlin
  • When Expression in Kotlin
  • While loop in Kotlin
  • Working of Loop:
  • Do while loop in Kotlin
  • Kotlin for loop
  • Use of Array With Loop
  • Use of String in Kotlin with function and Array
  • Break Statement in kotlin
  • Continue Statement
  • Functions in Kotlin

Advanced

  • Kotlin Standard Library Function
  • User-defined Functions
  • Calling of function in Kotlin
  • Kotlin Default Argument
  • Object-Oriented Programming
  • What is OOP?
  • Benefits
  • Kotlin Class
  • Kotlin Objects
  • How to access Members from the class?
  • Kotlin Constructors
  • Primary constructor
  • Primary Constructor and Initializer Blocks
  • Secondary constructor

More Advanced Topic

  • Kotlin Getter and Setters
  • Inheritance in Kotlin
  • Benefits of Inheritance
  • Kotlin Abstract Classes
  • Kotlin Abstract Class and Method
  • Kotlin Interfaces
  • Kotlin Nested and Inner Class
  • Kotlin Nested and Inner Class
  • Kotlin Sealed Classes
  • Kotlin Extension Function
  • Practice Questions

What is Kotlin?

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

Previously, Android developers were using JAVA for development, but now GOOGLE has officially declared Kotlin to be the official language for the development of Android applications.

Feature of 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 its standard library depends on the Java Class Library, but type inference allows its syntax to be more concise.
  • We write Kotlin code in a smaller number of lines of code as compared to JAVA for android Development.
  • It is interconvertible from java using IntelliJ IDEA.
  • First, it’s developed by JetBrains, who is known for making great developer tools. As such they’ve ensured that Kotlin has all the tools you need to do serious production development.
  • And now, Kotlin is officially supported by Google for Android.

Kotlin compiles a bytecode so that it can perform just as well as Java. It has the same compile-time checks as Java (and more, such as built-in nullity checks). And most importantly Kotlin’s language features and standard library features make it easy to use, efficient code.

  • It is a statically typed language.
  • A better language than Java
  • Andrey Breslav
  • Version 1.0 released in 2016
  • The mature version released Kotlin 1.2 in Nov 2017
  • You can create a mixture of Java and Kotlin
  • Three versions to Kotlin
  • Kotlin/JVM – compiles to Java bytecode (we’ll study)
  • Kotlin/JS – transpilers to JavaScript code
  • Kotlin/Native – compile to Native Binaries
  • Concise (i.e. a lot less code than Java)
    • Reduces the use of unnecessary declarations
    • Generates codes that have to be explicit in Java
    • Semi-colons not required
  • Safe
    • Avoid entire classes of errors such as Null Pointer Exceptions
    • Auto-casting of variables when checking types
  • Interoperable
    • It is compiled directly to Java bytecode and can be mixed with whatever platform it is running on. E.g. Java, Groovy, Scala or any other JVM languages.
    • It can work exactly the same in JVM and in web Browser
  • Tool-friendly
    • IntelliJ IDEA includes Kotlin plugins
    • Android Studio inherits Kotlin support

How to Install Kotlin?

Getting Started with Kotlin by installing specific Software.

  • Install JDK for your OS, using the following link

http://www.oracle.com/technetwork/java/javase/downloads/jdk10-downloads-4416644.html

Download and install the “Community” version of IntelliJ IDEA.

Installation of Git:

  • Go to your Command Window and type “git –version” to check the version of Git installed on your system.
  • If you don’t have “git” installed. Go to this link https://git-scm.com/

Kotlin- IntelLij idea

You can program with Kotlin from

  • the Command Line Eclipse plugins
  •  IntelliJ IDEA Product based on IDEA,
  • such as Android Studio First we’ll learn Kotlin and then, later on, develop Android apps IntelliJ IDEA is like the Xcode Playground for Swift.
Installation of IntelliJ idea after download
  • Kotlin first project Creation using Editor
Learn kotlin IntelliJ Interface
Learn kotlin IntelliJ Interface

Step 2: You should write the name of the project you want usually write in camel case letters.

Learn kotlin IntelliJ create project
Learn kotlin IntelliJ create project

 

Step 3: Click ok

Learn kotlin IntelliJ Welcome screen
Learn kotlin IntelliJ Welcome screen
Learn kotlin IntelliJ Project Screen
Learn kotlin IntelliJ Project Screen

Step 4: Make new Kotlin Class by click on new and then Click on Kotlin File/Class.

Learn kotlin IntelliJ Kotlin Class Creation
Learn kotlin IntelliJ Kotlin Class Creation

Step 5: Write the name of Class Usually we write in Camel Case letters.

Step 6: Class is made in Compiler and we have to write code of what we want.

Step 7: In this step right-click on the screen and make toolkit.

How java resides with kotlin?

Kotlin is a programming language and has its own architecture to allocate memory and output quality to the end-user. Here are the different scenarios where Kotlin compiler will work differently, whenever different languages such as Java and JavaScript are targeted.

Kotlin compiler creates a byte code and that byte code can run on the JVM, which is exactly the same as the byte code generated by the Java.class file. Whenever two-byte coded data are operating on the JVM, they can communicate with each other, and this is how an interoperable feature is established in Kotlin for Java.

learn kotlin How JAVA Code Resides with Kotlin
learn kotlin How JAVA Code Resides with Kotlin
learn kotlin How JAVA Code Resides with Kotlin
learn kotlin How JAVA Code Resides with Kotlin

If statement in Kotlin

If a certain section of the code is executed, if the test expression is evaluated to true. It may have a further optional clause. Codes inside the other clause are executed if the test expression is false.

Syntax


if (testExpression) {
// codes to run if testExpression is true
}
else {
// codes to run if testExpression is false
}
fun main(args: Array<String>) {
val number = -10
if (number > 0)
{
print("Positive numbers")
}
else
{
print("Negative number")
}
}

Output on Screen:
Negative number

When Expression in Kotlin

The when construct in Kotlin can be thought of as a substitute for the Java switch statement. It evaluates the code section of a number of alternatives.

Example


fun main(args: Array<String>) {
val a = 12
val b = 5
println("Enter operator either +, -, * or /")
val operator = readLine()
val result = when (operator) {
"+" -> a + b
"-" -> a - b
"*" -> a * b
"/" -> a / b
else -> "$operator operator is invalid operator."
}
println("result = $result")

Output on Screen
Enter operator either +, -, * or /
*
result = 60

The above program takes an input string from the user (Recommended Reading: Get String Input from the user in Kotlin). Suppose the user has entered *. In this case, the expression * b is evaluated and the value is assigned to the result of the variable. If none of the branch conditions is satisfied (the user entered anything except +,-, *, or/), the branch will be evaluated.


fun main(args: Array<String>) {
val a = 12
val b = 5
println("Enter operator either +, -, * or /")
val operator = readLine()
when (operator) {
"+" -> println("$a + $b = ${a + b}")
"-" -> println("$a - $b = ${a - b}")
"*" -> println("$a * $b = ${a * b}")
"/" -> println("$a / $b = ${a / b}")
else -> println("$operator is invalid")
}
}

Output on Screen:
Enter operator either +, -, * or /

12 – 5 = 7

While loop in Kotlin

Loop is used in programming to repeat a specific block of code until a certain condition is met (the test expression is false). Loops are the things that make computers interesting machines.

Imagine that you need to print a sentence 50 times on your screen. You’re going to need to use loops. You’ll learn about two loops while and do … while in this article, with the help of examples.

Basic Syntax:


while (testExpression) {
// codes inside body of while loop
}

Working of Loop:

  • The test expression within the parenthesis is a Boolean expression. If the test expression is evaluated to true, the statements inside the while loop will be executed.
  • The test expression is then evaluated again.
  • This process continues until the test expression is evaluated to be false.
  • If the test expression is evaluated to false, the loop will be terminated

Example:


fun main(args: Array<String>) {
var i = 1
while (i <= 5) {
println("Line $i")
++i
}
}

Line 1
Line 2
Line 3
Line 4
Line 5

Do while loop in Kotlin

The do … while loop is similar to the one key difference loop. The body of the do … while the loop is performed before the test expression is checked.

Syntax:


do {
// codes inside the body of do-while loop
} while (testExpression);

Example:


fun main(args: Array<String>) {
var sum: Int = 0
var input: String
do {
print("Enter an integer: ")
input = readLine()!!
sum += input.toInt()
} while (input != "0")
println("sum = $sum")
}

Output on Screen:
Enter an integer: 4
Enter an integer: 3
Enter an integer: 2
Enter an integer: -6
Enter an integer: 0
sum = 3

For loop in Kotlin

There is no typical loop in Kotlin, unlike Java and other languages. In Kotlin, the loop is used to iterate via elevations, arrays, maps and so on (anything provided via an iterator). The syntax of the Kotlin loop is:

Syntax:


for (item in collection) {
// body of a loop
}

Example:

fun main(args: Array<String>) {
for (i in 1..5) {
println(i)
}
}

Output on Screen:
1
2
3
4
5

Use of Array With Loop


fun main(args: Array<String>)
{
var language = arrayOf("Ruby", "Koltin", "Python" "Java")
for (item in language)
println(item)
}

Output on screen:
Ruby
Koltin
Python
Java

Use of String in Kotlin with function and Array


fun main(args: Array<String>)
{
var text= "Kotlin"
for (letter in text)
{ println(letter) } }

Output:
K
o
t
l
i
n

Break Statement in kotlin

It is sometimes desirable to close the loop immediately without checking the test expression. The nearest enclosing loop is terminated when it is encountered (without checking the test expression).

It is almost always used with if. Else construct. For example,

Syntax:


for (...) {
if (testExpression) {
break
}
}

Example:


fun main(args: Array<String>) {
for (i in 1..10) {
if (i == 5) {
break
}
println(i)
}
}

Output on Screen:
1
2
3
4

Continue Statement

It is almost always used with the if…else construct. For example,

while (testExpression1) {
// codes1
if (testExpression2) {
continue
}
// codes2
}

If testExpression2 is evaluated to true, continue which skips all codes inside while looping after it for that iteration.

Example:


fun main(args: Array<String>) {
for (i in 1..5) {
println("$i Always printed.")
if (i > 1 && i < 5) {
continue
}
println("$i Not always printed.")
}
}

Output on screen:

1 Always printed.
1 Not always printed.
2 Always printed.
3 Always printed.
4 Always printed.
5 Always printed.
5 Not always printed.

Functions in Kotlin

Kotlin Standard Library Function

The standard library functions are built-in functions in Kotlin that are readily available for use. For example,

  • print() is a library function that prints message to the standard output stream (monitor).
  • sqrt() returns the square root of a number (Double value)

User-defined Functions

As mentioned, you can create functions yourself. Such functions are called user-defined functions.

How to create a user-defined function in Kotlin?

Before you can use (call) a function, you need to define it. Here’s how you can define a function in Kotlin:

Syntax:

fun callMe() {
// function body
}

The fun keyword is used to define a function in Kotlin. The parenthesis) (in the above program is empty. It means because no argument is approved by such a function. The code inside the curly braces { } is the body of the function.

Calling of function in kotlin

fun addNumbers(n1: Double, n2: Double): Int {
val sum = n1 + n2
val sumInteger = sum.toInt()
return sumInteger
}
fun main(args: Array<String>) {
val number1 = 12.2
val number2 = 3.4
val result: Int
result = addNumbers(number1, number2)
println("result = $result")
}}

Output on screen:
result = 15

Kotlin Default Argument

In Kotlin, you can set the default values for the parameters in the function definition. If the function is called with arguments passed, these arguments are used as parameters.However, if the function is called without passing the argument(s), the default argument is used.

Example:


fun displayBorder(character: Char = '=', length: Int = 15) {
for (i in 1..length) {
print(character)
}
}
fun main(args: Array<String>) {
println("Output when no argument is passed:")
displayBorder()
println("\n\n'*' is used as a first argument.")
println("Output when first argument is passed:")
displayBorder('*')
println("\n\n'*' is used as a first argument.")
println("5 is used as a second argument.")
println("Output when both arguments are passed:")
displayBorder('*', 5)
}

Output on screen:
Output when no argument is passed:
===============
‘*’ is used as a first argument.
Output when first argument is passed:
***************
‘*’ is used as a first argument.
5 is used as a second argument.
Output when both arguments are passed:
*****

Object-Oriented Programming in Kotlin

  • Kotlin class and object:

Kotlin supports both functional and object-based programming. Kotlin promotes features such as higher-order functions, function types and lambdas, makes it a great choice for working in a functional programming style.

  • What is OOP?

In the object-oriented style of programming, you can divide a complex problem into smaller sets by creating objects.

Benefits of OOPs feature in Kotlin:

Re-usability

It means reusing some of the facilities rather than building them again and again. This is done by using a class. We can use ‘ n ‘ so many times as we need.

Data Redundancy

This is a condition created at the data storage area (you can say Databases) where the same piece of data is processed in two separate places. Data redundancy is, therefore, one of the greatest advantages of OOP. If a user wants similar functionality in multiple classes, he/she can go ahead by writing and inherit common class definitions for similar functionalities.

Code Maintenance

This feature is more necessary for any programming language, it helps users to rework in many ways. Maintaining and modifying existing codes with new changes is always easy and time-saving.

Security

Using the mechanism of data hiding and abstraction, we filter out limited exposure data, which means that we maintain security and provide the necessary data to view.

Design Benefits

If you are practising OOPs, the design benefit that the user will have is to design and fix things easily and eliminate (if any) risks. After a time when the program has reached some critical limits, it is easier to program all non-OOPs separately.

Reuse of code through inheritance in Kotlin

How to make Kotlin class?

In Kotlin, you need to define a class before you create objects. A class is an Object Template. We can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.

Since many houses can be made from the same description, we can create many objects from a class.

Syntax:


class ClassName {
// property
// member function
... .. ...
}

Example:


class Bulb {
// property (data member)
private var isOn: Boolean = false
// member function
fun turnOn() {
isOn = true
}
// member function
fun turnOff() {
isOn = false
}
}

Kotlin Objects

Only the specification for the object is specified when class is specified; no memory or capacity is allocated.

Example:

class Bulb {
// property (data member)
private var isOn: Boolean = false
// member function
fun turnOn() {
isOn = true
}
// member function
fun turnOff() {
isOn = false
}
}
fun main(args: Array<String>) {
val l1 = Lamp() // create l1 object of Lamp class
val l2 = Lamp() // create l2 object of Lamp class
}

How to access Members from the class?

l1.turnOn() // this is calling through object name and dot sign with function //name.


class Bulb
{
// property (data member)
private var isOn: Boolean = false
// member function
fun turnOn() {
isOn = true
}
// member function
fun turnOff() {
isOn = false
}
fun displayLightStatus(bulb: String) {
if (isOn == true)
println("$bulb bulb is on.")
else
println("$bulb bulb is off.")
}
}
fun main(args: Array<String>) {
val l1 = bulb () // create l1 object of Lamp class
val l2 = bulb () // create l2 object of Lamp class
l1.turnOn()
l2.turnOff()
l1.displayLightStatus("l1")
l2.displayLightStatus("l2")
}

Output on Screen:
l1 bulb is on.
l2 bulb is off.
How does it work?

  • Bulb class is created.
  • The class has a property isOn and three member functions turnOn(), turnOff() and displayLightStatus().
  • Two objects l1 and l2 of the Lamp class are created in the main() function.
  • Here, turnOn() function is called using l1 object: l1.turnOn(). This method sets isOn instance variable of l1 object to true.
  • And, turnOff() function is called using l2 object: l1.turnOff(). This method sets isOff instance variable of l2 object to false.
  • Then, displayLightStatus() function is called for l1 and l2 objects which prints appropriate message depending on whether isOn property is true or false.

class Bulb {
// property (data member)
private var isOn: Boolean = false
// member function
fun turnOn() {
isOn = true
}
// member function
fun turnOff() {
isOn = false
}
fun displayLightStatus() {
if (isOn == true)
println("bulb is on.")
else
println("bulb is off.")
}
}
fun main(args: Array<String>) {
val bulb = bulb ()
lamp.displayLightStatus()
}

Output on Screen:
bulb is off.

Kotlin Constructors

A builder is a succinct way of initializing class properties. It is a special member function named when an object is (created) instantiated. It’s slightly different how they function in Kotlin though.

There are two types of Constructors:

Primary constructor – concise way to initialize a class. The primary constructor is part of the class header.


class Person(val firstName: String, var age: Int) {
// class body
}

Example:


fun main(args: Array<String>) {
val person1 = Person("Joe", 25)
println("First Name = ${person1.firstName}")
println("Age = ${person1.age}")
}
class Person(val firstName: String, var age: Int) {
}

Output on Screen:
First Name = Joe
Age = 25

Primary Constructor and Initializer Blocks


fun main(args: Array<String>) {
val person1 = Person("joe", 25)
}
class Person(fName: String, personAge: Int) {
val firstName: String
var age: Int
// initializer block
init {
firstName = fName.capitalize()
age = personAge
println("First Name = $firstName")
println("Age = $age")
}
}

Output on Screen:
First Name = Joe
Age = 25

Secondary constructor – allows you to put additional initialization logic In Kotlin, one or more secondary constructors may also be in a class. They are generated using keyword constructor.

In Kotlin secondary builders aren’t that common. If you need to expand a class that provides several constructors that initialize the class in various ways, the most common usage of secondary constructor comes up. Be sure to check Kotlin Inheritance before you learn it.


class Log {
constructor(data: String) {
// some code
}
constructor(data: String, numberOfData: Int) {
// some code
}
}

Example:
d


class Person
{
var children: MutableList<Person> = mutableListOf<Person>();
constructor(parent: Person) {
parent.children.add(this)
}
}

Kotlin Getter and Setters:

Through programming, getters are used to get a property value. Likewise, setters are used to set property values.Getters and setters are optional in Kotlin and will be auto-generated if you don’t build them in your program.

Example


class Person {
var name: String = "defaultValue"
// getter
get() = field
// setter
set(value) {
field = value
}
}

How to call them?


val p = Person()
p.name = "jack"

Example:


fun main(args: Array<String>) {
val maria = Girl()
maria.actualAge = 15
maria.age = 15
println("Maria: actual age = ${maria.actualAge}")
println("Maria: pretended age = ${maria.age}")
val angela = Girl()
angela.actualAge = 35
angela.age = 35
println("Angela: actual age = ${angela.actualAge}")
println("Angela: pretended age = ${angela.age}")
}
class Girl {
var age: Int = 0
get() = field
set(value) {
field = if (value < 18)
value=18
else if (value >= 18 && value <= 30)
value
else
value-3
}
var actualAge: Int = 0
}

Inheritance in Kotlin

Heritage is a process whereby one class acquires another class’s property. An infant, for example, inherits his / her parent’s traits. Through inheritance, we are able to reuse existing class fields and methods. Inheritance thus promotes Reusability and is an important term for OOPs.

Benefits of Inheritance:

Regular use of once written code, i.e. reusability of code. For the number of subclasses in a hierarchy, one superclass may be used. No changes to be performed in all base classes, only changes are made in the parent class. Heritage is employed to produce more dominant artefacts.

Example:


open class Person(age: Int) {
// code for eating, talking, walking
}
class MathTeacher(age: Int): Person(age) {
// other features of math teacher
}
class Footballer(age: Int): Person(age) {
// other features of footballer
}
class Businessman(age: Int): Person(age) {
// other features of businessman
}

Example:


open class Person(age: Int, name: String) {
init {
println("My name is $name.")
println("My age is $age")
}
}
class MathTeacher(age: Int, name: String): Person(age, name) {
fun teachMaths() {
println("I teach in primary school.")
}
}
class Footballer(age: Int, name: String): Person(age, name) {
fun playFootball() {
println("I play for LA Galaxy.")
}
}
fun main(args: Array<String>) {
val t1 = MathTeacher(25, "Jack")
t1.teachMaths()
println()
val f1 = Footballer(29, "Christiano")
f1.playFootball()
}

Output on Screen:
My name is Jack.
My age is 25
I teach in primary school.
My name is Cristiano.
My age is 29
I play for LA Galaxy.

Tip on Class in Kotlin:

If the class has a primary constructor, the base must be initialized using the parameters of the primary constructor. In the above program, both derived classes have two parameters age and name, and both these parameters are initialized in primary constructor in the base class. This is an example of Base and Derived class the use of inheritance


open class Person() {
open fun displayAge(age: Int) {
println("My actual age is $age.")
}
}
class Girl: Person() {
override fun displayAge(age: Int) {
// calling function of base class
super.displayAge(age)
println("My fake age is ${age - 5}.")
}
}
fun main(args: Array<String>) {
val girl = Girl()
girl.displayAge(31)
}

Output on Screen:
My age is 31.
My fake age is 26.

Kotlin Abstract Classes

The abstract keyword like Java is used to define abstract classes in Kotlin. You can not instantiate an abstract class (you can’t construct abstract class objects). However, you can inherit subclasses from can them.

The members (properties and methods) of an abstract class are non-abstract unless you explicitly use the abstract keyword to make them abstract. Let’s take an example:

Example:


abstract class Person {
var age: Int = 40
fun displaySSN(ssn: Int) {
println("My SSN is $ssn.")
}
abstract fun displayJob(description: String)
}

It creates the abstract class Person. Did not construct class objects.

The class has a non-abstract property age and an unabstract displaying SSN form. If these members need to be overridden in the subclass, they should be labelled with the open keyword.

The class has display job of an abstract form. It also has no functionality, so it must be overridden in its subclasses.

Kotlin Abstract Class and Method

abstract class Person(name: String) {
init {
println("My name is $name.")
}
fun displaySSN(ssn: Int) {
println("My SSN is $ssn.")
}
abstract fun displayJob(description: String)
}
class Teacher(name: String): Person(name) {
override fun displayJob(description: String) {
println(description)
}
}
fun main(args: Array<String>) {
val Animesh = Teacher("Animesh")
jack.displayJob("I'm a mathematics teacher.")
jack.displaySSN(23123)
}

Output on Screen:
My name is Animesh.
I’m a mathematics teacher.
My SSN is 23123.

Kotlin Interfaces

Kotlin interfaces are similar to interfaces in Java 8. They can contain definitions of abstract methods as well as implementations of non-abstract methods. However, they can not contain any state.

Meaning, the interface may have property but it needs to be abstract or has to provide accessor implementations.

How to define an interface?

Syntax:


interface MyInterface {
var test: String // abstract property
fun foo() // abstract method
fun hello() = "Hello there" // method with default implementation
}
  • an interface MyInterface is created.
  • the interface has an abstract property test and an abstract method foo().
  • the interface also has a non-abstract method hello().

How to implement an interface in Kotlin?

Example


interface MyInterface {
val test: Int // abstract property
fun foo() : String // abstract method (returns String)
fun hello() { // method with default implementation
// body (optional)
}
}
class InterfaceImp : MyInterface {
override val test: Int = 25
override fun foo() = "Lol"
// other code
}
interface MyInterface {
val test: Int
fun foo() : String
fun hello() {
println("Hello there, Animesh")
}
}
class InterfaceImp : MyInterface {
override val test: Int = 25
override fun foo() = "Lol"
}
fun main(args: Array<String>) {
val obj = InterfaceImp()
println("test = ${obj.test}")
print("Calling hello(): ")
obj.hello()
print("Calling and printing foo(): ")
println(obj.foo())
}

Output on Screen:
test = 25
Calling hello(): Hello there, Animesh!
Calling and printing foo(): Lol


interface A {
fun callMe() {
println("From interface A")
}
}
interface B {
fun callMe() {
println("From interface B")
}
}
class C: A, B {
override fun callMe() {
super<A>.callMe()
super<B>.callMe()
}
}
fun main(args: Array<String>) {
val obj = C()
obj.callMe()
}

Output on screen:
From interface A
From interface B

Kotlin Nested and Inner Class

Syntax:


class Outer {
... .. ...
class Nested {
... .. ...
}
}

Example:


class Outer {
val a = "Outside Nested class."
class Nested {
val b = "Inside Nested class."
fun callMe() = "Function call from inside Nested class."
}
}
fun main(args: Array<String>) {
// accessing member of Nested class
println(Outer.Nested().b)
// creating object of Nested class
val nested = Outer.Nested()
println(nested.callMe())
}

Output on Screen:
Inside Nested class.
Function call from inside Nested class.

Kotlin Inner Class


class Outer {
val foo = "Outside Nested class."
class Nested {
// Error! cannot access member of outer class.
fun callMe() = foo
}
}
fun main(args: Array<String>) {
val outer = Outer()
println(outer.Nested().callMe())
}

The above code won’t compile because we tried to access foo property of Outer class from inside Nested class.

In order to solve this issue, you need to mark the nested class with inner to create an inner class. Inner classes carry a reference to an outer class and can access outer class members.

Example:


class Outer {
val a = "Outside Nested class."
inner class Inner {
fun callMe() = a
}
}
fun main(args: Array<String>) {
val outer = Outer()
println("Using outer object: ${outer.Inner().callMe()}")
val inner = Outer().Inner()
println("Using inner object: ${inner.callMe()}")
}

Output on Screen:
Using outer object: Outside Nested class.
Using inner object: Outside Nested class.

More Advanced Topics on Kotlin

Kotlin Sealed Classes

Sealed classes are used when a category from a limited. set (restricted hierarchies) may have only one of the forms.


class Expr
class Const(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr
fun eval(e: Expr): Int =
when (e) {
is Const -> e.value
is Sum -> eval(e.right) + eval(e.left)
else ->
throw IllegalArgumentException("Unknown expression")
}

The base class Expr has two derivative classes Const (represents a number) and Sum (represents the sum of two expressions) in the program above. Here, when communicating, it is compulsory to use another branch for the default condition.

Now, if you derive a new subclass from Expr class, the compiler won’t detect anything as else branch handles it which can lead to bugs. It would have been better if the compiler issued an error when we added a new subclass.

To solve this problem, you can use a sealed class. As mentioned, the sealed class restricts the possibility of creating subclasses. And, when you handle all subclasses of a sealed class in a when expression, it’s not necessary to use else branch.

Kotlin Extension Function

Suppose a class with new features needs to be expanded. You either derive a new class in most programming languages or use some type of design pattern to do this.

However, in Koltin, you can also use an extension function to extend a class with new functionality. Basically, an extension function is a member function of a class that is defined outside the class.

For example, you need to use a method to the String class that returns a new string with first and last character removed; this method is not already available in String class. You can use an extension function to accomplish this task.

Example:


fun String.removeFirstLastChar(): String = this.substring(1, this.length - 1)
fun main(args: Array<String>) {
val myString= "Hello Everyone"
val result = myString.removeFirstLastChar()
println("First character is: $result")
}

Output on screen:
First character is:
ello Everyon

Practice Questions That can be solved by using Kotlin Language

  1. Add a series of numbers input by the user and find the average of these numbers. It is not known in advance how many values will be input.
  2. Display the status of the students (Pass or Fail) based on the marks entered by the user. It is not known in advance how many marks will be entered.
  3. Find the hypotenuse of the right-angled triangle given its two sides using Pythagorean Theorem.
  4. A company manufactures a line of traffic cones. It requires painting its cones in different colours. The company has hired you to write a program that will compute the surface area of the cone, and the cost of painting it, given its radius, height and the cost per square foot of three different colours of paint. The surface area of the cone can be calculated using formula
  5. Mother had just filled the cookie jar when the three children went to bed. That night one child woke up, ate half of the cookies and went back to bed. Later, the second child woke up, ate half of the remaining cookies and went back to bed. Still later, the third child woke up, ate half of the remaining cookies, leaving 5 cookies in the jar. How many cookies were in the jar to begin with? Find a generic solution to this problem.
  6. Find and display the sum of numbers from 1 to n where n is input by the user.
  7. Display a line of n stars.
  8. Compute the cost per square foot of living space for a house, given the dimensions (Length, Width) of the house, the number of stories, the size of the non-living space (garage, closets), the total cost of the house.
  9. Given a positive integer number, find whether the number is even or odd.
  10. Given a positive integer number, find display if the number is a prime number.
  11. Find the slope of a line through two points using formula m =. The values of y1, y2, x1 and x2 are given. If x1 equals x2, the line is vertical and the slope is undefined. If y1 equals y2, the line is horizontal.

Ref: Great books on Kotlin

Share and Enjoy !

1 thought on “Learn Kotlin Step By Step Fast and Free”

  1. Pingback: Ultimate Starter Kit Android Developer Guides To Learn Quick And Fast In 30 Mins - Tech Travel Hub

Leave a Comment

Your email address will not be published. Required fields are marked *