Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introduction to Kotlin

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers. →
Avatar for Faruk Faruk
September 17, 2020

Introduction to Kotlin

Introduction to Kotlin

Avatar for Faruk

Faruk

September 17, 2020

Other Decks in Programming

Transcript

  1. • Android • JVM • iOS, macOS, watchOS, and tvOS

    • Windows • Linux • JavaScript (KotlinJs) • WebAssembly • LLVM (Kotlin/Native)
  2. • 2011 - Born • 2015 - v1.0 released •

    2017 - Google announced first-class support for Kotlin on Android. • 2017 - Sharing code between JVM and JavaScript platforms • 2018 - Coroutines support for asynchronous programming. • 2019 - Google announced that the Kotlin programming language is now its preferred language for Android app developers. • 2020 - Support for Apple's platforms.
  3. val immutable = "Can't change" immutable = "New value" //

    Compile error var mutable = "Can change" mutable = "New value"
  4. var canBeNull: String? = "abc" canBeNull = null // ok

    var notNull: String = "abc" notNull = null // Compile error
  5. if (some != null && some.length() > 0){ // }

    if (!some.isNullOrEmpty()) { // }
  6. // simple name in template: var a = 1 val

    s1 = "a is $a" a = 2 // arbitrary expression in template: val s2 = "${s1.replace("is", "was")}, but now is $a"
  7. // Smart cast if (obj is String) { // obj

    is automatically cast to String in this branch return obj.length }
  8. val items = listOf("apple", "banana", "kiwi") val array = arrayOf(1,

    2, 3) val numbers = mutableListOf(1, 2) val nums = arrayListOf(1) val map = mapOf( "one" to 1, "two" to 2 )
  9. fun describe(obj: Any): String = when (obj) { 1 ->

    "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Unknown" }
  10. fun convert(x: String): Int { return when { x ==

    "unknown" -> 0 x.length < 11 -> 1 else -> 2 } }
  11. fun reformat(str: String, normalizeCase: Boolean = true, wordSeparator: Char =

    ' ') { ... } reformat(str) reformat(str, false, '_') reformat(str, wordSeparator = '_')
  12. infix fun Int.shl(x: Int): Int { ... } // call

    the function using the infix notation 1 shl 2 // is the same as 1.shl(2)
  13. // Higher order functions fun <T> ArrayList<T>.myFilter(condition: (T) -> Boolean):

    ArrayList<T>{ val result = arrayListOf<T>() for (item in this){ if (condition(item)){ result.add(item) } } return result }
  14. inline fun onlyIf(check: Boolean, operation: () -> Unit) { if

    (check) { operation() } } onlyIf(shouldPrint) { println(“Hello, Kotlin”) } // which will be inlined to this if (shouldPrint) { // no need to create lambda println(“Hello, Kotlin”) }
  15. // Older way val logger = Logger.getLogger(SomeLogger::class.java) inline fun <reified

    T> loggerOf() = Logger.getLogger(T::class.java) // Kotlin way val logger = loggerOf<SomeLogger>
  16. fun Int?.orZero() = this ?: 0 val myInt:Int? = null

    println("${myInt.orZero()}") // will print 0
  17. Functions are final by default Arguments are always final Functions

    can be defined in a file outside of a class
  18. // Getter & setter var email:String = "" set(value) {

    if (value.isValidEmail()){ field = value } }
  19. // lambdas val fruits = listOf( "banana", "avocado", "apple", "kiwifruit"

    ) fruits .filter { it.startsWith("a") } .sortedBy { it } .map { it.toUpperCase() } .forEach { println(it) }
  20. class MyClass() { // non-null, but not initialized lateinit var

    myView: View override fun onCreate() { // initialized here myView = findViewById(R.id.view) } }
  21. // Initialized at first call val preference: String by lazy

    { sharedPreferences.getString(PREFERENCE_KEY) }
  22. class Example { var username: String by Delegate("key") fun main(){

    println(username) // Reads from database username = "newName" // Writes to databse } } class Delegate(private val key: String) { operator fun getValue(thisRef: Example, prop: KProperty<*>): String { return thisRef.readFromDb(key) } operator fun setValue(thisRef: Example, prop: KProperty<*>, value: String) { thisRef.writeToDb(key, value) } }
  23. // All classes and methods are final by default class

    MyClass { ... } open class Base { fun thisIsFinal() { ... } open fun notFinal() { ... } } class NewClass: Base { override fun notFinal() { ... } }
  24. sealed class NetworkResult{ data class Success(val result: String): NetworkResult() data

    class Failure(val error: Error): NetworkResult() } // one observer for success and failure fun parse(data: NetworkResult){ when(data) { is Success -> showResult(data.result) // smart cast to Success is Failure -> showError(data.error) // smart cast to Failure } }
  25. data class User( val name: String = "", val age:

    Int = 0 ) val user = User("name", 20) val newUser = user.copy(age = 33) // User("name", 33)
  26. // Destructing val user = User("Jane", 35) val (name, age)

    = user println("$name, $age years of age") // prints "Jane, 35 years of age"
  27. // T -> operation -> T User user = new

    User(); user.name = "Name; user.save(); val user = User().apply { // `this` represents User name = "Name" save() }
  28. // Builder class MyBuilder { var name = "" ...

    fun setName(newName: String) = builder.apply(name = newName) ... }
  29. // T -> operation -> Y UserVm wrap(User user){ if

    (user != null) { return new UserVm(user); } return null; } fun wrap(user: User?) = user?.let { UserVm(it) }
  30. DSL

  31. fun result() = html { head { title {+"XML encoding

    with Kotlin"} } body { h1 {+"XML encoding with Kotlin"} p {+"this format can be used as an alternative markup to XML"} a(href = "http://kotlinlang.org") {+"Kotlin"} p {+"some text"} p { for (arg in args) +arg } } }
  32. fun html(init: HTML.() -> Unit): HTML { val html =

    HTML() html.init() return html } fun head(init: Head.() -> Unit) : Head { val head = Head() head.init() children.add(head) return head } html { head { ... } body { ... } }
  33. fun main() = runBlocking { // this: CoroutineScope launch {

    delay(200L) println("Task from runBlocking") } coroutineScope { // Creates a coroutine scope launch { delay(500L) println("Task from nested launch") } delay(100L) println("Task from coroutine scope") // This line will be printed before the nested launch } println("Coroutine scope is over") // This line is not printed until the nested launch completes }
  34. • 2018 - Github Fastest growing language https://octoverse.github.com/2018/projects#lan guages •

    4th language most loved by developers https://insights.stackoverflow.com/survey/2019# most-popular-technologies • 70% of the top 1000 Android apps use Kotlin https://developer.android.com/kotlin/stories
  35. • https://kotlinlang.org • https://github.com/JetBrains/kotlin • https://try.kotlinlang.org/ • https://en.wikipedia.org/wiki/Kotlin_(programming_language) • https://www.thoughtworks.com/radar/languages-and-frameworks/ko

    tlin • https://spring.io/blog/2017/01/04/introducing-kotlin-support-in-sprin g-framework-5-0 • https://blog.duolingo.com/migrating-duolingos-android-app-to-100-ko tlin/