Friday, 2 February 2018

Kotlin: infix functions

In kotlin, you can call functions in infix notation.  Infix functions are defined using the keyword ‘infix’. Infix functions must have a single parameter.

You can make a function as infix function, if the function
a.   Is a member function (or) extension function
b.   Has only single parameter
c.   Is marked with keyword infix

Infix member function
class EvenNumber {

 infix fun isEven(num: Int): Boolean {
  if (num % 2 == 0) return true
  return false
 }

}

As you see isEven is defined as infix function using the keyword infix.

How to call isEven function?
var is5Even = obj isEven 5    // Same can be called obj.isEven(5)


InfixDemo.kt
class EvenNumber {

 infix fun isEven(num: Int): Boolean {
  if (num % 2 == 0) return true
  return false
 }

}

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

 var is5Even = obj isEven 5    // Same can be called obj.isEven(5)
 var is6Even = obj isEven 6    // Same can be called obj.isEven(5)

 println("Is 5 even number $is5Even")
 println("Is 6 even number $is6Even")
}

Output
Is 5 even number false
Is 6 even number true


Infix extension funcitons
In kotlin, you can extend the functionality of a class, by using extension functions.


For example, below code add doubleEven function to the class EvenNumber.
infix fun EvenNumber.doubleEven(num: Int): Int {

 if (isEven(num)) {
  return num * 2
 }
 return -1
}


InfixDemo.kt
class EvenNumber {

 infix fun isEven(num: Int): Boolean {
  if (num % 2 == 0) return true
  return false
 }

}

infix fun EvenNumber.doubleEven(num: Int): Int {

 if (isEven(num)) {
  return num * 2
 }
 return -1
}

fun main(args: Array<String>) {

 var obj = EvenNumber()

 var double6 = obj doubleEven 6   // Same can be called obj.doubleEven(5)

 println("Double 6 $double6")
}


Output
Double 6 12






Previous                                                 Next                                                 Home

Thursday, 1 February 2018

Kotlin: Single Expression functions

When a function returns single expression, you can omit curly braces.

Ex
fun square(num: Int) = num * num
fun cube(num: Int) = num * num * num

FunctionDemo.kt
fun square(num: Int) = num * num
fun cube(num: Int) = num * num * num

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

Output
Square of 5 is 25
Cube of 5 is 125



Previous                                                 Next                                                 Home

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