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