*/ val a: Int = 1 // Explicit type val b = 2 // Type inferred /* Mutable */ var mutable = 2 mutable = 4 // Reassignment val world = "World!" val helloWorld1 = "Hello $world" // -> Hello World! val helloWorld2 = "Hello ${world.replace("!", "!!!")}" // -> Hello World!!!
java.util.Date val now = Date() now.time // equivalent to now.getTime() Document doc = new Document("Welcome Kotlin!", "Giacomo Bresciani", new Date()); String author = doc.getAuthor();
"underage" else “adult" • If • When (Java’s switch with superpowers) val ageTitle = when { age < 18 -> "underage" age in 18..64 -> "adult" else -> "senior" } • Try-Catch val int: Int? = try { "23d".toInt() } catch (nfe: NumberFormatException) { null } Kotlin Features
class ViewState { object Loading: ViewState() data class Error(val message: String): ViewState() data class Ready(val content: String): ViewState() } • Definition • When fun render(currentState: ViewState) = when (currentState) { ViewState.Loading -> print("Loading...") is ViewState.Error -> print(currentState.message) is ViewState.Ready -> print(currentState.content) } Kotlin Features
to query collections public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> public fun <T> List<T>.asReversed(): List<T> public inline fun <T> Iterable<T>.find(predicate: (T) -> Boolean): T? Kotlin Features public inline fun <T> T.apply(block: T.() -> Unit): T public inline fun <T, R> T.let(block: (T) -> R): R public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R • Functions implementing idiomatic patterns
SumTest : Spek({ describe("sum() function") { it("should return the sum of first number plus the second number") { val sum = sum(2, 4) assertEquals(6, sum) } } }) • KotlinTest - flexible and comprehensive testing tool “my string".length shouldBe 9 “hello" shouldNot haveSubstring(“olleh")