From Java to Kotlin

Life is great and Kotlin is Here !!!

What’s Kotlin ?

Kotlin is a statically typed programming language that runs on the JVM and also can be compiled to JavaScript source code and is reliant on Java code from the existing Java Class Library, such as the collections framework

History

  • Start from 2010, development lead (Andrey Breslav)
  • In July 2011 JetBrains unveiled Project Kotlin
  • In February 2012, JetBrains open sourced Kotlin
  • Kotlin v1.0 was released on February 15, 2016
  • At Google I/O 2017, Google announced first-class support for Kotlin on Android.

What can Kotlin do ?

  • Server-side development
  • Android development
  • Compile to JavaScript source code
  • Kotlin Script

Java VS Kotlin

Kotlin Specific

  • Functions(Anonymous, Lambda, Inline…)
  • Extensions
  • Ranges
  • Null Safety
  • Class(data class, enum class, Sealed Class)
  • Exception
  • Objects

Anonymous Function

 1
 2
 3
 4
 5
 6
 7
 8
 9
10

val sum = fun(a: Int, b: Int): Int  { 
    return a + b 
}

// or

val sum = fun(a: Int, b: Int) = a + b

println(sum(3, 5))

Default Arguments

1
2
3
4
5
6
fun sayHello(greeting: String = "Hello Kotlin") {
    println(greeting)
}

sayHello() // print 'Hello Kotlin'
sayHello("Hello World") // print 'Hello World'

Named Arguments

1
2
3
4
5
6
7
fun playBasketball(withPerson: String, atTime: Int, feelTired: Boolean) {
    //...
}

playBasketball("Kobe", 4, true)

playBasketball(atTime=4, withPerson="Kobe", feelTired = true)

Variable number of arguments

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
fun varArgs(vararg args: Int) {
    args.forEach {
        print(it)
    }
}

varArgs(1,2,3,4,5)

val arr = intArrayOf(6,7,8,9)
varArgs(1,2,*arr,4,5)

Lambda

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
val sum = { x: Int, y: Int -> x + y }
// or 
val sum: (Int, Int) -> Int = { x, y -> x + y}

val arr = listOf(1,2,3,4,5)
arr.filter({i -> i and 1 == 0 })
arr.filter({it and 1 == 0})
arr.filter {
    it and 1 == 0
}

Inline Function

1
2
3
4
5
6
7
inline fun hello(str: String, (String) -> Unit) {
    //...
}

inline fun foo(inlined: ()->Unit, noinline notInlined: () -> Unit) {
    //...
}

Inline Function can improve performance, but it may cause the generated code to grow

Extension

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// extension functions
fun Int.triple():Int {
    return this * 3
}

3.triple() // 9

// extension properties
val Int.dp: Int
    get() = this * 4

4.dp // 16

Ranges

1
2
3
4
for ( i in 1..4) print(i) // 1234
for ( i in 1 until 4) print(i) // 123
for ( i in 4 downTo 1) print(i) // 4321
for ( i in 4 downTo 1 step 2) print(i) // 42
  • CharRange
  • IntRange
  • LongRange
  • “..” -> rangeTo()

Null Safety

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var str: String = "Hello" // Non-null type
str = null // error

var nullableStr: String? = "World" // Nullable type
nullableStr = null

nullableStr?.length ?: return
println(nullableStr.length)
// or
nullableStr!!.length

Class and Inheritance

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// final default
class Person(val firstName: String, val lastName: String) {
    fun walk() {
        println("$firstName $lastName is walking")
    }
}

// Inheritance
open class Base(p: Int)
class Derived(p: Int) : Base(p)

class MyView : View {
    constructor(ctx: Context) : super(ctx)
    constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs)
}

Data class

1
data class User(val name: String, val age: Int)

The compiler automatically derives the following members from all properties declared in the primary constructor:

  • equals()/hashCode()
  • toString()
  • componentN()
  • copy()

Data classes have to fulfill the following requirements:

  • The primary constructor needs to have at least one parameter;
  • All primary constructor parameters need to be marked as val or var;
  • Data classes cannot be abstract, open, sealed or inner;
  • Providing explicit implementations for the componentN() and copy() functions is not allowed.

Enum Class

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
enum class LightState {
    ON {
        override fun switch() = OFF
    },
    OFF {
        override fun switch() = ON
    };

    abstract fun switch(): LightState
}

val LightState.state: Int
    get() = if (this == LightState.OFF) 0 else 1

LightState.OFF.switch().state // 1

Visibility Modifiers

Package Level

  • private (visible inside the file containing the declaration)
  • public (default, visible everywhere)
  • internal (visible everywhere in the same module)

Class & Interface Level

  • private (visible inside this class only)
  • protected (same as private + visible in subclasses too)
  • public (default, visible everywhere)
  • internal (any client inside this module)

Exception

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
throw Exception("Help!!")

val number: Int? = try {
    "Glow2017".toInt()
}
catch (e: NumberFormatException){
    null
}
finally {
    // optional block
}

Objects

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// anonymous inner class
var listener = object: TouchListener {

    override fun onLongClick() {
    }

    override fun onClick() {
    }

}
// singleton
object Logger {

    fun info(info: String) {
        println("info: $info")
    }

}
  • Type Alias
1
typealias Func = (Int, Int) -> Int
  • Operator overloading
1
2
3
operator fun Vector.plus(param: Vector): Vector {
    return Vector(this.a + param.a, this.b + param.b)
}
  • Destructuring Declarations
1
val (paramA, paramB) = vecA

Java Interop

Calling java code from kotlin

  • Getter and Setter
  • Method returning void
  • Escaping for Java identifiers that are keywords in Kotlin
  • Null-Safety and Platform Types
  • Java Reflection

Calling Kotlin from Java

  • Properties
  • Package-Level Functions
  • Static fields and methods
  • Handling signature clashes with @JvmName
  • Overloads Generation
  • Checked Exceptions

More

  • Delegation
  • Coroutines
  • Generic
  • Annotation
  • Reflection

Readings

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy