What is kotlin?
Kotlin is a statically-typed programming language that runs on the Java Virtual Machine (JVM) and can also be compiled into JavaScript or native code. It was developed by JetBrains, the company behind the popular IntelliJ IDEA Java IDE. It was designed to be more concise and expressive than Java, while still being fully interoperable with it. Some of its neat features include:
Extension functions
Kotlin allows you to add new functions to existing classes without having to inherit from them or use any design patterns such as Decorator. These are called extension functions and are defined using the fun
keyword and the receiver type
before the function name.
fun String.removeFirstAndLastChar(): String {
return this.substring(1, this.length - 1)
}
val str = "abc"
println(str.removeFirstAndLastChar()) // prints "b"
Null safety
Kotlin has built-in support for null safety, which helps you avoid null reference exceptions. You can use the ?
operator to declare that a variable can be null, and the !!
operator to force a nullable type to be non-null. You can also use the ?.
operator to access a method or property of a nullable object safely.
fun printLength(str: String?) {
val length = str?.length ?: -1
println(length)
}
printLength("abc") // prints 3
printLength(null) // prints -1
Higher-order functions
Kotlin supports higher-order functions, which are functions that take other functions as arguments or return them as results. This allows you to write more concise and expressive code and use functional programming techniques such as lambda expressions.
fun performAction(x: Int, y: Int, action: (Int, Int) -> Int): Int {
return action(x, y)
}
val result = performAction(2, 3) { x, y -> x + y }
println(result) // prints 5
Coroutines
Kotlin's coroutines allow you to write asynchronous code that is easy to read and write, and that avoids common problems such as callback hell. Coroutines are lightweight threads that can be suspended and resumed, and they are well-suited for tasks such as network requests and file I/O.
import kotlinx.coroutines.*
suspend fun main() = coroutineScope {
launch {
delay(1000)
println("Kotlin Coroutines World!") //prints after 1 sec
}
println("Hello")
}
Hope this helps you learn something new.
!!