Friday, 9 February 2018

Kotlin: Declare extensions as members of other class


You can define extension to class ‘A’ in other class ‘B’. Inside the extension function, you can use the methods of class ‘A’ directly.

class A {
         fun sayHello() {
                 println("Hello")
         }

         fun sayWelcome() {
                 println("Welcome")
         }
}

Let me define other class ‘B’ that add extension function to B.

class B {
         fun A.welcomeUser() {
                 sayHello()
                 sayWelcome()
         }
}

Find the below working application.

HelloWorld.kt
package com.sample.test

class A {
 fun sayHello() {
  println("Hello")
 }

 fun sayWelcome() {
  println("Welcome")
 }
}

class B {
 fun A.welcomeUser() {
  sayHello()
  sayWelcome()
 }

 fun welcomeUser() {
  var obj = A()
  obj.welcomeUser()
 }
}

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

 obj.welcomeUser()

}

Output
Hello
Welcome





Previous                                                 Next                                                 Home

Kotlin: Scope of extension functions

If you define an extension function to a class ‘C1’, in other class ‘C2’ then the extension is visible only in ‘C2’, not from outside of ‘C2’.

class Arithmetic {
         fun sum(a: Int, b: Int): Int {
                 return a + b
         }
}

Let me define an extension function to Arithmetic class in other class ‘DemoClass1’.

class DemoClass1 {
         fun Arithmetic.sub(a: Int, b: Int): Int {
                 return a - b
         }


         fun getSubtraction(a: Int, b: Int): Int {
                 var obj = Arithmetic()
                 return obj.sub(a, b)
         }
}

when you try to access the extension function from main method, you will get an error.

fun main(args: Array<String>) {
         var obj = Arithmetic()
        
         obj.sub(10, 20)

}

Find the complete working application.

HelloWorld.kt
class Arithmetic {
 fun sum(a: Int, b: Int): Int {
  return a + b
 }
}

class DemoClass1 {
 fun Arithmetic.sub(a: Int, b: Int): Int {
  return a - b
 }


 fun getSubtraction(a: Int, b: Int): Int {
  var obj = Arithmetic()
  return obj.sub(a, b)
 }
}

fun main(args: Array<String>) {
 var obj = Arithmetic()
 
 obj.sub(10, 20)

}

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

ERROR: Unresolved reference: sub (22, 6)

Scope of top level extension functions
If you define extension functions directly under a package, then other packages can use these extension functions by importing them.

MathUtil.kt
package com.sample.util

class Arithmetic {
 fun sum(a: Int, b: Int): Int {
  return a + b
 }
}

Let me define new kotlin file ‘MathUtilExtensions’, it implements all the extension functions.


MathUtilExtensions.kt
package com.sample.util

fun Arithmetic.sub(a: Int, b: Int): Int = a - b
fun Arithmetic.mul(a: Int, b: Int): Int = a * b
fun Arithmetic.div(a: Int, b: Int): Int = a / b


As you notify above snippet, I defined three extension functions sub, mul, div to the class Arithmetic.

I can use these extension functions from other packages by importing them.

import com.sample.util.sub
import com.sample.util.mul
import com.sample.util.div


Test.kt
package com.sample.test

import com.sample.util.sub
import com.sample.util.mul
import com.sample.util.div

import com.sample.util.Arithmetic

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

 var result1 = obj.sum(10, 20)
 var result2 = obj.sub(10, 20)
 var result3 = obj.mul(10, 20)
 var result4 = obj.div(10, 20)

 println("Sum of 10 and 20 $result1")
 println("Subtraction of 10 and 20 $result2")
 println("Multiplication of 10 and 20 $result3")
 println("Division of 10 and 20 $result4")

}

Output
Sum of 10 and 20 30
Subtraction of 10 and 20 -10
Multiplication of 10 and 20 200
Division of 10 and 20 0


Previous                                                 Next                                                 Home

Thursday, 8 February 2018

Kotlin: Extensions to companion object

In my previous post, I explained how to set extensions to an existing class. In this post, I am going to explain how to set extensions to companion object.

Syntax
fun Type.Companion.functionName(arguments) = definition

C is capital in ‘Companion’

Ex
         fun TestClass.Companion.sum(a: Int, b: Int): Int {
                 return a + b
         }

Just like the normal companion functions call, you can call extension functions.

TestClass.sum(10, 20)

Find the below working application.

HelloWorld.kt
class TestClass {
 companion object {
  fun sayHello() {
   println("Hello")
  }
 }
}

fun main(args: Array<String>) {
 fun TestClass.Companion.sum(a: Int, b: Int): Int {
  return a + b
 }

 var sumOfNumbers = TestClass.sum(10, 20)

 println("Sum of 10 and 20 $sumOfNumbers")
}

Output
Sum of 10 and 20 30



Previous                                                 Next                                                 Home

Wednesday, 7 February 2018

Kotlin: Extensions

Unlike java, you can extend the functionality of a class without creating a subclass to it. This is done by extensions. By using extensions, you can extend both the properties and methods.

How to add extension function to a type?
Prefix the function name with receiver type.

Syntax
Type.functionName(arguments) : returnType = definition

Let me explain with detailed example.

class Arithmetic {
         fun sum(a: Int, b: Int) = a + b
         fun sub(a: Int, b: Int) = a - b
}

I can add new function that multiply two numbers to the Arithmetic class using extensions like below.

fun Arithmetic.mul(a: Int, b: Int) = a * b

Find below working application.

HelloWorld.kt
class Arithmetic {
 fun sum(a: Int, b: Int) = a + b
 fun sub(a: Int, b: Int) = a - b
}

fun main(args: Array<String>) {
 fun Arithmetic.mul(a: Int, b: Int) = a * b

 var obj = Arithmetic()

 var sumOf10And20 = obj.sum(10, 20)
 var subOf10And20 = obj.sub(10, 20)
 var mulOf10And20 = obj.mul(10, 20)

 println("Sum of 10 and 20 $sumOf10And20")
 println("Subtraction of 10 and 20 $subOf10And20")
 println("Multiplication of 10 and 20 $mulOf10And20")
}

Output
Sum of 10 and 20 30
Subtraction of 10 and 20 -10
Multiplication of 10 and 20 200

How to add extension property?
It is like adding extension function to a type. Remember Extension property cannot be initialized because it has no backing field, their behavior is defined only by using getter and setter methods.
Ex
         val Arithmetic.PI: Double
                 get() = 3.14

Find the below working application.


HelloWorld.kt
class Arithmetic {
 fun sum(a: Int, b: Int) = a + b
 fun sub(a: Int, b: Int) = a - b
}

class Test {
 val Arithmetic.PI: Double
  get() = 3.14

 fun getPI(): Double {
  var obj = Arithmetic()
  return obj.PI
 }
}

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

 println("Value of PI : ${obj.getPI()}")
}


Output
Value of PI : 3.14


Previous                                                 Next                                                 Home

Tuesday, 6 February 2018

Kotlin: Access specifiers

Access specifiers are used to restrict the data access. Kotlin support 4 access specifiers.
a.   private
b.   protected
c.   internal
d.   public

If you do not specify any access specifier, then public is used by default.

Where can I apply access specifiers?
You can apply access specifiers on Classes, interfaces, constructors, objects, functions, properties and their setter methods. Getters always have the same visibility as the property.

Below table summarizes the access specifiers.
Access Specifier
Description
Private
Members defined with private access specifier are visible only in same scope.
Protected
Members defined with protected access specifier are visible in the same class and all the sub classes of this class.
Internal
Members defined with internal access specifier are visible in the same module.
Public
Members defined with public access specifier are visible from everywhere.

public access specifier
If you mark an element with public modifier, then this element can be accessed from anywhere. If you do not specify any access modifier to an element, the access is public by default.

Test.kt
package com.sample.model

class Test {
 public var i : Int = 10
 var j : Int = 11
}

HelloWorld.kt
import com.sample.model.Test

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

 println("i = ${obj.i}")
 println("j = ${obj.j}")

 obj.i = 88
 obj.j = 99

 println("i = ${obj.i}")
 println("j = ${obj.j}")

}

Output

i = 10
j = 11
i = 88
j = 99

private access specifier
If you declare an element using private access specifier, then the code that is declared in the same scope can access it, no other code can access it.


Test.kt
package com.sample.model

private var totalObjs: Int = 0

class DemoClass1 {
 constructor() {
  totalObjs++
 }

 companion object {
  fun getTotalObjs() = totalObjs
 }
}

class DemoClass2 {
 constructor() {
  totalObjs++
 }
}

HelloWorld.kt
import com.sample.model.*

fun main(args: Array<String>) {
 var obj1 = DemoClass1()
 var obj2 = DemoClass2()

 println("Total objects created : ${DemoClass1.getTotalObjs()}")

 var obj3 = DemoClass1()
 var obj4 = DemoClass2()

 println("Total objects created : ${DemoClass1.getTotalObjs()}")
}

Output
Total objects created : 2
Total objects created : 4

Protected access specifier
Members defined with protected access specifier are visible in the same class and all the sub classes of this class.


Test.kt

open class DemoClass1 {
 protected var i: Int = 10
}

class DemoClass2 : DemoClass1() {
 fun getValueOfI(): Int {
  return i
 }
}

Note
If you override a protected member and do not specify the visibility explicitly, the overriding member will also have protected visibility.

internal access specifier
Members defined with internal access specifier are visible in the same module. A module is a collection of kotlin resources compiled together.


Test.kt

open class DemoClass1 {
 internal var i: Int = 10
}

class DemoClass2 : DemoClass1() {
 fun getValueOfI(): Int {
  return i
 }
}

Note

a.   Local variables, local functions and classes do not have access specifiers



Previous                                                 Next                                                 Home

Monday, 5 February 2018

Kotlin: Packages

Package is a name space that provides a way to organise interfaces, classes, functions in a way to avoid naming collisions.

Packages are like Directories. For Example, you can keep all the audio files in one directory, video files in other directory and text files in one directory. Similarly, A project can contain several files, so it is always good to organise them in consistent way. 

Benefits of Packages
1. Packages offers modularity, like we can logically group the things, for Example, all file related classes and interfaces can be in package named “file”, all the system related classes and interfaces in package named “system”, all the Graphical user interfaces classes can go to ‘userInterface’ package etc.,

2.We can apply access restrictions using access specifiers protected,private, internal and public.

3. Name Space Collisions avoided

4. Programmers or users can easily determine which classes are related based on package grouping

How to Create a Package
By using package keyword, you can define a package.

Syntax
package packageName;

for example, you can place all the data structure related classes and interfaces in package named ‘collections’.

Ex
package collections;

The package statement must be the first line in the source file.

How to create a package in Eclipse?
Right click on Kotlin project -> New -> Package
It opens below window, give the package name as ‘com.sample.model’.
Click on Finish button. You can see the updated project structure.
Define a class in the package ‘com.sample.model’
Right click on the package 'com.sample.model' -> New -> Other
Select Kotlin -> Kotlin Class
After that it opens a window, there give the class name as Employee and press Finish button.

How to import the package into other classes?
By using ‘import’ statement we can import other packages.

Ex
import com.sample.model.Employee

Find the below working application.

Employee.kt

package com.sample.model

class Employee {
 lateinit var firstName: String
 lateinit var lastName: String
 lateinit var id: String
}

HelloWorld.kt

import com.sample.model.Employee

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

 obj.firstName = "Chamu"
 obj.lastName = "Gurram"
 obj.id = "Id1234"

 println("First Name : ${obj.firstName}")
 println("Last Name : ${obj.lastName}")
 println("Id : ${obj.id}")

}

Output

First Name : Chamu
Last Name : Gurram
Id : Id1234


Previous                                                 Next                                                 Home

Saturday, 3 February 2018

Kotlin: Anonymous functions

In my previous post, I explained about lambda expressions, one disadvantage of lambda expression is, you can’t specify the return type. Anonymous functions are similar to lambda expressions, where you can specify return type.

Ex
fun(x: Int): Int = 2 * x

As you see above snippet, it is anonymous function, which doubles the value. The syntax of anonymous function is just like a function, except it do not have function name.

You can also specify body of the anonymous function in curly braces like below.

fun(x: Int): Int {return 2 * x}

A 'return' expression required in a anonymous function with a block body ('{...}')

Find the below working application.

FunctionDemo.kt
fun processData(arr: IntArray, functionToProcess: (Int) -> Int): IntArray {
 var result = IntArray(arr.size)

 var counter = 0

 for (ele in arr) {
  result[counter++] = functionToProcess.invoke(ele)
 }

 return result
}

fun printArray(arr: IntArray) {
 for (ele in arr) {
  print("$ele ")
 }
 println()
}

fun main(args: Array<String>) {
 var arr1 = IntArray(5, { i -> i })

 println("Elements in arr1 are")
 printArray(arr1)

 /* Higher order function using anonymous function */
 var doubleArrayElements = processData(arr1, fun(x: Int): Int { return 2 * x })

 println("Elements in doubleArrayElements are")
 printArray(doubleArrayElements)

 doubleArrayElements = processData(arr1, fun(x: Int): Int = 2 * x)

 println("Elements in doubleArrayElements are")
 printArray(doubleArrayElements)
}

Output

Elements in arr1 are
0 1 2 3 4 
Elements in doubleArrayElements are
0 2 4 6 8 
Elements in doubleArrayElements are
0 2 4 6 8

You can omit the parameter types, if they can be inferred from context.

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

You can also omit the return type for the anonymous function in non-block notation.

Ex
fun(x)= 2 * x



Previous                                                 Next                                                 Home