Monday, 29 January 2018

Kotlin: unit (or) void functions

Unit returning functions are similar to void functions in Java. If a function do not return any value, its return type is Unit.

UnitDemo.kt
fun welcome(name: String) : Unit {
 println("Welcome $name")
 
 return Unit // You can simply call return
}

fun main(args: Array<String>) {
 var returnValue = welcome("Hari krishna")
 println("Returned value is $returnValue")
}


Output
Welcome Hari krishna
Returned value is kotlin.Unit

Specifying the type ‘Unit’  and returning Unit from unit functions is optional.


UnitDemo.kt
fun welcome(name: String) {
 println("Welcome $name")
}

fun main(args: Array<String>) {
 var returnValue = welcome("Hari krishna")
 println("Returned value is $returnValue")
}


Previous                                                 Next                                                 Home

Kotlin: varargs : Variable number of arguments

By using 'vararg' modifier, you can define a function that takes variable number of arguments. If you would like to know, basics of vararg in Java, you can go through my below post.

https://self-learning-java-tutorial.blogspot.com/2014/02/varargs-methods-with-variable-number-of.html

Ex
fun sumOf(vararg numbers: Int): Int {

}

Above function takes variable number of integer arguments and return an integer.

VarargsDemo.kt
fun sumOf(vararg numbers: Int): Int {
 var sum: Int = 0;

 for (i in numbers) {
  sum = sum + i
 }

 return sum
}

fun main(args: Array<String>) {
 println("Sum of (1, 2, 3) : ${sumOf(1, 2, 3)}")
 println("Sum of (13, 22, 13, 5, 3) : ${sumOf(13, 22, 13, 5, 3)}")
}


Output
Sum of (1, 2, 3) : 6
Sum of (13, 22, 13, 5, 3) : 56




Previous                                                 Next                                                 Home

Sunday, 28 January 2018

Kotlin: Function default arguments

We can specify default values to function parameters. These default values are used, when you do not specify any values to the function arguments while calling.

fun readFile(offset: Int = 0, numOfBytes: Int = 1024) {
         println("Reading file from offset : $offset, numOfBytes : $numOfBytes ")
}

readFile()
Since readFile() called with no arguments, offset and numOfBytes are set to default values.

readFile(10)
Since readFile() called with one argument 10, offset is set to 10 and numOfBytes is set to default value 1024.

readFile(10, 300)
Since readFile() called with two arguments, offset is set to 10 and numOfBytes is set to 1024.  

DefaultValues.kt
fun readFile(offset: Int = 0, numOfBytes: Int = 1024) {
 println("Reading file from offset : $offset, numOfBytes : $numOfBytes ")
}

fun main(args: Array<String>) {
 readFile()
 readFile(10)
 readFile(10, 300)
}

Output
Reading file from offset : 0, numOfBytes : 1024 
Reading file from offset : 10, numOfBytes : 1024 
Reading file from offset : 10, numOfBytes : 300


Named arguments further enhance this feature, when you would like to set the values to some of the arguments and remaining take default values.

readFile(numOfBytes=500)
Since readFile() is called by specifying numOfBytes to 500

FunctionsDemo.kt
fun readFile(offset: Int = 0, numOfBytes: Int = 1024) {
 println("Reading file from offset : $offset, numOfBytes : $numOfBytes ")
}

fun main(args: Array<String>) {
 readFile(numOfBytes=500)
}

Output
Reading file from offset : 10, numOfBytes : 1024, bufferSize : 500



Previous                                                 Next                                                 Home

Saturday, 27 January 2018

Kotlin: Call functions using parameter names

In Kotlin, you can call the functions using parameter names, this is similar to 'Keyword arguments' feature in python.

fun printEmployee(id: String, firstName: String, lastName: String, designation: String) {
         println("\nid : $id\nfirstName : $firstName\nlastName : $lastName\ndesignation : $designation")
}

In kotlin, you can call the function by using the parameter names.
printEmployee(id = "1", firstName = "krishna", lastName = "Gurram", designation = "engineer")

One advantage of specifying parameter names is, you can change the arguments order while calling the function.
printEmployee(designation = "engineer", firstName = "krishna", lastName = "Gurram", id = "1")

KeyWordArgsDemo.kt

fun printEmployee(id: String, firstName: String, lastName: String, designation: String) {
 println("\nid : $id\nfirstName : $firstName\nlastName : $lastName\ndesignation : $designation")
}


fun main(args: Array<String>) {
 printEmployee("1", "krishna", "Gurram", "Engineer")

 printEmployee(id = "1", firstName = "krishna", lastName = "Gurram", designation = "engineer")
 printEmployee(designation = "engineer", firstName = "krishna", lastName = "Gurram", id = "1")
}

Output

id : 1
firstName : krishna
lastName : Gurram
designation : Engineer

id : 1
firstName : krishna
lastName : Gurram
designation : engineer

id : 1
firstName : krishna
lastName : Gurram
designation : engineer


Previous                                                 Next                                                 Home

Friday, 26 January 2018

Kotlin: functions

Function is a block of statements, used to reuse the code. In kotlin, there are two types of funcitons.
a.   Kotlin library functions (ex: print, sqrt etc.,)
b.   User defined functions.

In this tutorial series, I am going to focus on user defined functions.

In Kotlin, functions are defined using 'fun' keyword.

Syntax
fun functionName(parameters) : returnType{

}

If you do not specify a returnType, it treats it as a void method. parameters are optional.

Parameters must be typed and multiple parameters are separated by comma (,).

Syntax
fun functionName(param1 : type, param2: type …. paramN:type) : returnType{

}

Ex
// void function with no arguments
fun printWelcomeMessage() {
         println("Welcome buddy")
}

// void function with one argument
fun printWelcomeMessage(name: String) {
         println("Welcome $name")
}

// void method with two arguments
fun printWelcomeMessage(firstName: String, lastName: String) {
         println("Welcome [$firstName, $lastName]")
}

//non-void function with no arguments
fun getWelcomeMessage(): String {
         return "Welcome"
}

//non-void function with one argument
fun getWelcomeMessage(name: String): String {
         return "Welcome $name"
}

//non-void function with two arguments
fun getWelcomeMessage(firstName: String, lastName: String): String {
         return "Welcome [$firstName, $lastName]"
}
  

FunctionsDemo.kt

// void function with no arguments
fun printWelcomeMessage() {
 println("Welcome buddy")
}

// void function with one argument
fun printWelcomeMessage(name: String) {
 println("Welcome $name")
}

// void method with two arguments
fun printWelcomeMessage(firstName: String, lastName: String) {
 println("Welcome [$firstName, $lastName]")
}

//non-void function with no arguments
fun getWelcomeMessage(): String {
 return "Welcome"
}

//non-void function with one argument
fun getWelcomeMessage(name: String): String {
 return "Welcome $name"
}

//non-void function with two arguments
fun getWelcomeMessage(firstName: String, lastName: String): String {
 return "Welcome [$firstName, $lastName]"
}


fun main(args: Array<String>) {
 printWelcomeMessage()

 printWelcomeMessage("Ram")

 printWelcomeMessage("Ram", "Krishna")

 var message = getWelcomeMessage()
 println("${message}")

 message = getWelcomeMessage("Ram")
 println("${message}")

 message = getWelcomeMessage("Ram", "Krishna")
 println("${message}")
}

Output

Welcome buddy
Welcome Ram
Welcome [Ram, Krishna]
Welcome
Welcome Ram
Welcome [Ram, Krishna]

If your function body has only one statement, then you can omit the braces {}

Ex
fun square(x: Int) = x * x
fun cube(x: Int) = x * x * x
fun printMessage() = "Hello World"


FunctionsDemo.kt

fun square(x: Int) = x * x
fun cube(x: Int) = x * x * x
fun printMessage() = "Hello World"

fun main(args: Array<String>) {
 println("Square of 10 is ${square(10)}")
 println("Cube of 10 is ${cube(10)}")
 println(printMessage())
}

Output

Square of 10 is 100
Cube of 10 is 1000
Hello World



Previous                                                 Next                                                 Home

Thursday, 25 January 2018

Kotlin: ?: Elvis operator

By using Elvis operator, for any nullable reference 'n', we can say 'If n is not null use it, else use some default value'.

var name = emp?.name ?: "DefaultEmp"

Above statement return employee name, if emp is non-null, else return "DefaultEmp"

Find the below working application.

Test.kt
package com.sample.test

class Department {
 var departmentName: String = ""
 var departmentId: String = ""
}

class Employee {
 var name: String = ""
 var department: Department? = null
}

private fun printEmpDetails(emp: Employee?) {
 var name = emp?.name ?: "DefaultEmp"
 var departmentName = emp?.department?.departmentName ?: "DefaultDept"
 var departmentId = emp?.department?.departmentId ?: "DefaultDept"


 println("name : $name")
 println("departmentName : $departmentName")
 println("departmentId : $departmentId")
 println("\n")
}

fun main(args: Array<String>) {
 var emp1: Employee? = null

 var emp2 = Employee()
 emp2.name = "Chamu"

 var emp3 = Employee()

 var department = Department()
 department.departmentId = "DEP01"
 department.departmentName = "CSC"
 emp3.department = department
 emp3.name = "Krishna"

 printEmpDetails(emp1)
 printEmpDetails(emp2)
 printEmpDetails(emp3)
}

Output

name : DefaultEmp
departmentName : DefaultDept
departmentId : DefaultDept


name : Chamu
departmentName : DefaultDept
departmentId : DefaultDept


name : Krishna
departmentName : CSC
departmentId : DEP01



Previous                                                 Next                                                 Home

Kotlin: ?.: Safe call operator: handle nullable types

In my previous post, I explained nullable types. In this post, I am going to explain, how can we handle nullable types using ?. (Safe call operator).

Ex:
emp?.name

?. (Safe call operator) return employee name if the emp is not null, otherwise null.

Safe calls are used in chains, for example, below statements return the deparementName and departmentId by using safe call operator.

         var departmentName = emp?.department?.departmentName
         var departmentId = emp?.department?.departmentId

Find the below working application.

Test.kt

package com.sample.test

class Department {
 var departmentName: String = ""
 var departmentId: String = ""
}

class Employee {
 var name: String = ""
 var department: Department? = null
}

private fun printEmpDetails(emp: Employee?) {
 var name = emp?.name
 var departmentName = emp?.department?.departmentName
 var departmentId = emp?.department?.departmentId


 println("name : $name")
 println("departmentName : $departmentName")
 println("departmentId : $departmentId")
 println("\n")
}

fun main(args: Array<String>) {
 var emp1: Employee? = null

 var emp2 = Employee()
 emp2.name = "Chamu"

 var emp3 = Employee()

 var department = Department()
 department.departmentId = "DEP01"
 department.departmentName = "CSC"
 emp3.department = department
 emp3.name = "Krishna"

 printEmpDetails(emp1)
 printEmpDetails(emp2)
 printEmpDetails(emp3)
}

Output

name : null
departmentName : null
departmentId : null


name : Chamu
departmentName : null
departmentId : null


name : Krishna
departmentName : CSC
departmentId : DEP01




Previous                                                 Next                                                 Home

Tuesday, 23 January 2018

Kotlin: Abstract classes

An abstract class can have methods without implementation. Abstract class is defined using ‘abstract’ keyword.

Ex
interface Arithmetic{
 fun sum(x : Int, y : Int) : Int
 fun sub(x : Int, y : Int) : Int
 fun mul(x : Int, y : Int) : Int
 fun div(x : Int, y : Int) : Int
}

abstract class ArithmeticImpl : Arithmetic{
 override fun sum(x : Int, y : Int) : Int{
  return x + y
 }
 
 override fun sub(x : Int, y : Int) : Int{
  return x - y
 }
}

You can’t define instance (object) to abstract class.

Abstract method
Just like how you defined abstract class, you can define abstract method (method without implementation) using the keyword ‘abstract’.

abstract class ArithmeticImpl : Arithmetic{
 override fun sum(x : Int, y : Int) : Int{
  return x + y
 }
 
 override fun sub(x : Int, y : Int) : Int{
  return x - y
 }
 
 abstract fun areaofCircle(radius : Int) : Int
}

In the above snippet, I declared ‘areaOfCircle’ as abstract method. Any concrete class that is extending this abstract class must provide implementation to all the abstract methods.


class ConcreteArithmetic : ArithmeticImpl() {
 override fun mul(x: Int, y: Int): Int {
  return x * y
 }

 override fun div(x: Int, y: Int): Int {
  return x / y
 }

 override fun areaofCircle(radius: Int): Double {
  return 3.14 * radius * radius
 }
}

Find the below working application.


HelloWorld.kt

interface Arithmetic {
 fun sum(x: Int, y: Int): Int
 fun sub(x: Int, y: Int): Int
 fun mul(x: Int, y: Int): Int
 fun div(x: Int, y: Int): Int
}

abstract class ArithmeticImpl : Arithmetic {
 override fun sum(x: Int, y: Int): Int {
  return x + y
 }

 override fun sub(x: Int, y: Int): Int {
  return x - y
 }

 abstract fun areaofCircle(radius: Int): Double
}

class ConcreteArithmetic : ArithmeticImpl() {
 override fun mul(x: Int, y: Int): Int {
  return x * y
 }

 override fun div(x: Int, y: Int): Int {
  return x / y
 }

 override fun areaofCircle(radius: Int): Double {
  return 3.14 * radius * radius
 }
}

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

 var sumOf10And20 = obj.sum(10, 20)
 var subOf10And20 = obj.sub(10, 20)
 var mulOf10And20 = obj.mul(10, 20)
 var divOf10And20 = obj.div(10, 20)
 var areaOfCircle = obj.areaofCircle(5)

 println("sumOf10And20 = $sumOf10And20")
 println("subOf10And20 = $subOf10And20")
 println("mulOf10And20 = $mulOf10And20")
 println("divOf10And20 = $divOf10And20")
 println("areaOfCircle = $areaOfCircle")

}


Output

sumOf10And20 = 30
subOf10And20 = -10
mulOf10And20 = 200
divOf10And20 = 0
areaOfCircle = 78.5






Previous                                                 Next                                                 Home

Monday, 22 January 2018

Kotlin: Access super class of outer class from inner class

By using the super keyword qualified with outer class name, we can access the super class of the outer class. Let’s me explain with an example.

Ex

Find below working application.

HelloWorld.kt
open class GrandParentClass {
 fun grandParentFunction() {
  println("I am in grand parent class")
 }
}

open class ParentClass : GrandParentClass() {
 fun parentClass() {
  println("I am in parent class")
 }

 inner class ChildInnerClass {
  fun printInfo() {
   parentClass()
   super@ParentClass.grandParentFunction()
  }
 }
}

fun main(args: Array<String>) {
 var innerObj = ParentClass().ChildInnerClass()

 innerObj.printInfo()
}

Output
I am in parent class
I am in grand parent class



Previous                                                 Next                                                 Home

Saturday, 20 January 2018

JavaDoc: @value: Display constant values

@value tag is used to display constant values.

The values of all the constants that are tagged with @value tag are displayed in 'Constant Field Values' section.

Arithmetic.java

package com.java.tags;

/**
 * 
 * @author Hari Krishna
 * 
 * @since 1.0
 */
public interface Arithemtic {

 /**
  * The value of PI is {@value}
  */
 public static final double PI = 3.14;

 /**
  * 
  * @param radius
  *            Radius of the Circle
  * 
  * @return area of the circle.
  * 
  * @since 1.1
  */
 public double areaOfCircle(int radius);

}



Previous                                                 Next                                                 Home

Javadoc: @link: Used to create inline links

@link tag is used to create inline links that can refer to the documentation for the specified package, class, or member name of a referenced class.

Syntax
{@link package.class#member label}

Refer constant of same class
/**
 * Calculates the area of circle. It uses value of {@link #PI} in
 * calculation.
 *
 */
public double areaOfCircle(int radius);

Refer method of same class
/**
 * Prints the area of circle. It internally calls {@link #areaOfCircle(int)}
 * method
 *
 */
public void printAreaOfCircle(int radius);

Refer method of other class
/**
 * Calculate the squalre root of the parameter a. It internally calls
 * {@link java.lang.Math#sqrt(double)}
 *
 * @return square root of a
 */
public default double sqrt(double a) {
         return Math.sqrt(a);
}

Find the below example.


Arithmetic.java
package com.java.tags;

/**
 * 
 * @author Hari Krishna
 * 
 * @since 1.0
 */
public interface Arithemtic {

 /**
  * The value of PI is {@value}
  */
 public static final double PI = 3.14;

 /**
  * Calculates the area of circle. It uses value of {@link #PI} in
  * calculation.
  * 
  * @param radius
  *            Radius of the Circle
  * 
  * @return area of the circle.
  * 
  * @since 1.1
  */
 public double areaOfCircle(int radius);

 /**
  * Prints the area of circle. It internally calls {@link #areaOfCircle(int)}
  * method
  * 
  * @param radius
  *            Radius of the Circle.
  */
 public void printAreaOfCircle(int radius);

 /**
  * Calculate the squalre root of the parameter a. It internally calls
  * {@link java.lang.Math#sqrt(double)}
  * 
  * @param a
  *            Operand
  * @return square root of a
  */
 public default double sqrt(double a) {
  return Math.sqrt(a);
 }

}



Previous                                                 Next                                                 Home

Javadoc: @inheritDoc: Inherit the documentation

{@inheritDoc} tag is used to inherit the documentation from the nearest inheritable class or implementable interface into the current documentation comment at this tag's location.

You can use @inheritedDoc tag in description block, or in the text arguments of @return, @param, and @throws tags.

Usage of @inheritDoc tag in description block
When you use @inheritDoc tag in description block, the main description is copied from a class or interface up the hierarchy.

/**
 * {@inheritDoc}
 */
@Override
public void welcomeEmployee(String empName) {
         System.out.println("Hello " + empName);
}

ABCOrg.java
package com.java.tags;

/**
 * 
 * @author Hari Krishna
 * 
 * @since 1.0
 */
public class ABCOrg {

 /**
  * Print welcome message to employee.
  * 
  * @param empName
  *            Employee Name
  */
 public void welcomeEmployee(String empName) {
  System.out.println("Hello " + empName);
 }

}

XYZOrg.java

package com.java.tags;

public class XYZOrg extends ABCOrg{

 /**
  * {@inheritDoc}
  */
 @Override
 public void welcomeEmployee(String empName) {
  System.out.println("Hello " + empName);
 }
}


Javadoc for the class XYZOrg generated like below.

Usage of @inheritDoc tag in tag descriptions of @return, @param, and @throws
When you use @inheritDoc tag in tag descriptions of @return, @param and @throws tags, the tag text is copied from the corresponding tag up the hierarchy.

ABCOrg.java
package com.java.tags;

/**
 * 
 * @author Hari Krishna
 * 
 * @since 1.0
 */
public class ABCOrg {

 /**
  * Print welcome message to employee.
  * 
  * @param empName
  *            Employee Name
  */
 public void welcomeEmployee(String empName) {
  System.out.println("Hello " + empName);
 }

}


XYZOrg.java
package com.java.tags;

public class XYZOrg extends ABCOrg{

 /**
  * Welcome Employee.
  * 
  * @param empName {@inheritDoc}
  */
 @Override
 public void welcomeEmployee(String empName) {
  System.out.println("Hello " + empName);
 }
}


Javadoc for the class XYZOrg generated like below.



Previous                                                 Next                                                 Home