Kotlin miniguide #6 Functions interoperability with Java

It’s possible to call kotlin functions from within Java.

The following Kotlin code:


//file name Util.kt

@file:JvmName("Utils")

package test

fun displayName() {... }

Is compiled to:


package test

class Utils() {

public static void displayName( ){...}

}

And it can be called this way from Java:


test.Utils.displayName();

More details here

Kotlin miniguide #5 Functions declaration


//typical function declaration

fun sum(a: Int, b: Int) : Int {

    return a+b

}

//function expression
fun sum(a: Int, b: Int) = a+b

//default parameters

fun payClerck(pay: Double , tip: Double = 1.0) : Double {

    return pay+ tip

}

//calling

payClerck(10.)

payClerck(10., 2.)

//using named parameters it is possible to change their

// order when calling the function

payClerck(tip = 1., pay = 2.0)

In kotlin functions are first class citizens:
A first-class citizen […] is an entity which supports all the operations generally available to other entities. These operations typically include being passed as an argument, returned from a function, modified, and assigned to a variable. (Wikipedia)

Functions do not need to be declared inside a class.

Functions can be declared locally

Kotlin miniguide #3 Conditional

If can be used as an expression and its result assigned to a variable:


val a = 1

val b = 2

val msg = if (a > b ) "a greater than b" else "a less than b"

Kotlin doesn’t have a switch but there is something very cool called when:


val a = 1

when(a) {

    0 -> print("a is zero")

    in (1..10) ->print("a in range")

    else ->print("a not in range")

}

Kotlin miniguide #2 Compilation


//file Main.kt

class Person() {
fun greet() {
println("Hello");
}
}

fun main(args: Array) {
Person().greet()
}

In the example above I have created a file with extension kt and inside it I have added a class and the main function. In Kotlin, each class compiles to a separate .class, which gives me Person.class; plus, the main fun, which is not contained in any class, will generate a Mainkt.class

The Mainkt.class contains a public class named Mainkt with a public static method called main