Source - Run on Java VM 6 & + - Static typing (type inference) - Modern language - Easy to Read & Learn - Concise & Fast to write - Fully interoperable with Java - 1st grade tooling
Lambdas - Data class - Smart cast - Null safety - Lazy property - Default values for function parameters - Extension Functions - No more ; - Single-expression functions - When expression - let, apply, use, with - Collections - Android Extensions Plugin
typing and null-safety make a big difference. "Some people say Kotlin has 80% the power of Scala, with 20% of the features" * "Kotlin is a software engineering language in contrast to Scala which is a computing science language." * Swift and Kotlin are VERY similar. Swift is LLVM based and has C interop while Kotlin is JVM based and has Java interop. * Quotes from Kotlin: The Ying and Yang of Programming Languages
b = 1 // `Int` type is inferred val c: Int // Type required when no initializer is provided c = 1 // definite assignment var x = 5 // `Int` type is inferred x += 1 Infered values Mutable values val : constant value var : variable value
be null ! // use ? the safe call operator val length = stringB?.length //Value or null - length is type Int? val length = stringB!!.length // Value or explicit throw NPE - length is type Int 22 Safety with Optionals var stringA: String = "foo" stringA = null //Compilation error - stringA is a String (non optional) var stringB: String? = "bar" // stringB is an Optional String stringB = null //ok Safe call with ?. or Explicit call !!. Optional value
: String // Compilation error lateinit var s : String // late initialized variable // if s is not set throw an NPE fun testHello() { s = "Hello $name" //… } Lazy, Delegates … Late initialization // set length default value manually val length = if (stringB != null) stringB.length else -1 //or with the Elvis operator val length = stringB?.length ?: -1 Default Value & Elvis Operator
Resource { val name = "Name" } println(" my resource is : ${Resource.name}") class StringCalculator{ companion object{ val operators = arrayOf("+","-","x","/") } } println(" my operators are : ${StringCalculator.operators}") Object (good old singleton ;-) ) Companion Object
2 -> print("x == 2") else -> { // Note the block print("x is neither 1 nor 2") } } Flow Control (replace your old if blocks) when (x) { in 1..10 -> print("x is in the range") in validNumbers -> print("x is valid") !in 10..20 -> print("x is outside the range") else -> print("none of the above") } Pattern Matching in <range> -> is <type> -> expression -> when (s) { is String -> print("s is a string") else -> print("s is not a string") }
view -> popLocationDialog(view) } A lambda expression or an anonymous function is a “function literal”, i.e. a function that is not declared, but passed immediately as an expression - A lambda expression is always surrounded by curly braces, - Its parameters (if any) are declared before -> (parameter types may be omitted), - The body goes after -> (when present). numberString.split("\n").flatMap { it.split(separator) } .map(Integer::parseInt) .map(::checkPositiveNumber) .filter { it <= 1000 } .sum()
… } val (separator, numberString) = extractDelimiter(input) data class User(var name : String,var age : Int) val toto = User("toto",42) // … val (name,age) = toto Returning two values with Pair Destructured values
"c","aa") list.filter { it.startsWith("a") } // immutable map val map = mapOf("a" to 1, "b" to 2, "c" to 3) for ((k, v) in map) { println("$k -> $v") } // mutable map val map2 = HashMap<String,String>() // direct map access map2["a"] = "my value" println(map2["a"]) // range for (i in 1..100) { //... }
String{ val (name,age) = user return "[name=$name][age=$age]" } } fun WhatIsyourAge(user : User){ println("Your age is ${user.age}") } data class User (val name: String, val age : Int){ companion object{ fun sayHello(user : User){ println("Hello ${user.name}") } } } User u = new User("toto",42); User.Companion.sayHello(u); UserUtilsKt.WhatIsyourAge(u); System.out.println("stringify : "+UserSingleton.INSTANCE.stringify(u)); Kotlin code Calling Kotlin from Java
-Dfile.encoding=UTF-8 org.gradle.parallel=true # Kotlin kotlin.incremental=true # Android Studio 2.2+ android.enableBuildCache=true In your gradle.properties https://medium.com/keepsafe-engineering/kotlin-vs-java-compilation-speed-e6c174b39b5d#.k44v7axsk
+= 'src/main/kotlin' } } apply plugin: 'com.android.application' apply plugin: ‘kotlin-android’ apply plugin: ‘kotlin-android-extensions’ // if use extensions In your build.gradle