Kotlin lang

Kotlin lang

Droidup 2.0 Tbilisi; Language design, futures and base syntax overview

F024125c7e2196ee1116c133a364a093?s=128

Jemo Mgebrishvili

November 20, 2016
Tweet

Transcript

  1. { Kotlin } Statically typed language for the JVM, Android

    and the browser. Developed by JetBrains First stable release February 15, 2016.
  2. { Syntax }. var and val var <propertyName>: <Type> =

    [property initializer] get() // optional set() // optional //example var str: String = “kotlin is awesome" OR var str = “kotlin is awesome"
  3. { Syntax }. method declaration fun <methodName> : <ReturnType> //example

    fun saySomthing() : String { return “kotlin is awesome" } OR fun saySomthing() = “kotlin is awesome"
  4. { Syntax } 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") }
  5. { Syntax } for ((k, v) in map) { println("$k

    -> $v") } someObject?.let { // execute this block if not null } fun foo(param: Int) { val result = if (param == 1) { "one" } else if (param == 2) { "two" } else { "three" } }
  6. { Syntax } .inheritance all classes by default are finals

    open class Base { open fun v() {} fun nv() {} } class Derived() : Base() { override fun v() {} }
  7. { Syntax } .inheritance open class A { open fun

    f() { print("A") } fun a() { print("a") } } interface B { fun f() { print("B") } fun b() { print("b") } } class C() : A(), B { // The compiler requires f() to be overridden: override fun f() { super<A>.f() // call to A.f() super<B>.f() // call to B.f() } }
  8. { Syntax } .inner classes class A { // implicit

    label @A inner class B { // implicit label @B fun foo() { val a = this@A // A's this val b = this@B // B's this } } }
  9. Billion-dollar mistake Tony Hoare My goal was to ensure that

    all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement.
  10. { null safety } nullable and non-nullable types var str:

    String = “kotlin is awesome" str = null // compilation error… str is non-nullable type var str: String? = “kotlin is awesome" str = null // ok... str now can be null val length = name.length // compilation error val length = name?.length // ok
  11. { null safety } nullable and non-nullable types var name:

    String? = “some string" if (name != null){ length = name.length }else{ length = 0 } or more shortly val length = name?.length ?: 0
  12. { Default parameters } fun tmpMethod(a: Int = -10, b:

    Int = 5, c: Int = 0){ print(a + b + c) } ---------------------------------------------------------------- tmpMethod(1) // 7 tmpMethod(2) // -8 tmpMethod(1,2,3) // 6 tmpMethod(b = 0, a = 2) // 2
  13. { Delegated Properties } Lazy & Observable

  14. { Delegated Properties } val lazyValue: String by lazy {

    println("computed!") "Hello" } fun main(args: Array<String>) { println(lazyValue) println(lazyValue) } This example prints: computed! Hello Hello
  15. { Delegated Properties } var age: Int by Delegates.observable(0) {

    prop, old, new -> println("$old -> $new") } age = 10 // 0 -> 10 age = 11 // 10 -> 11
  16. { No more Utils }.utilHell

  17. { Extensions } Extension methods & Extension properties

  18. { Extensions }.methods val nullableString : String? = null if

    (nullableString.isNullOrEmpty()){ // nullableString is null or empty }
  19. { Extensions }.methods var myObject : MyClass? = null if

    (myObject.isNull()){ // my object is null }
  20. { Extensions }.methods var myObject : MyClass? = null if

    (myObject.isNull()){ // my object is null } fun MyClass?.isNull() : Boolean { return this == null } OR fun MyClass?.isNull() = this == null
  21. { Extensions }.methods fun Activity.toast(msg: String, toastLength: Int = Toast.LENGTH_SHORT)

    { Toast.makeText(this, msg, toastLength).show() } fun Fragment.toast(msg: String, toastLength: Int = Toast.LENGTH_SHORT) { Toast.makeText(this, msg, toastLength).show() }
  22. { Extensions }.properties val myList = listOf(1,2,3,4,5) val lastIndex =

    myList.lastIndex // lastIndex = 4 --------------------------------
  23. { Extensions }.properties val myList = listOf(1,2,3,4,5) val lastIndex =

    myList.lastIndex // lastIndex = 4 -------------------------------- val <T> List<T>.lastIndex: Int get() = size - 1
  24. { Lambdas } Collections.sort(items, { t1, t2 -> t1.name.compareTo(t2.name)}) ---------------------------------------------------------------------------------------------------------

    in java Collections.sort(items, new Comparator<MyClass>() { @Override public int compare(MyClass t1, MyClass t2) { return t1.getName().compareTo(t2.getName()); } });
  25. { Higher-Order funcitons} fun <T, R> List<T>.map(transform: (T) -> R):

    List<R> { val result = arrayListOf<R>() for (item in this) result.add(transform(item)) return result } val doubled = items.map { it * 2 } fun <T> max(collection: Collection<T>, less: (T, T) -> Boolean): T? { var max: T? = null for (it in collection) if (max == null || less(max, it)) max = it return max } val less = {a:Int,b:Int -> a > b}
  26. Example of SqliteDatabase transaction in android ------------------------------------------------------------------------------------ db.beginTransaction() try {

    db.delete("tableName","firstName =?", arrayOf("Jake")) db.setTransactionSuccessful() }finally { db.endTransaction() }
  27. Example of SqliteDatabase transaction in android ------------------------------------------------------------------------------------ db.beginTransaction() try {

    // do work here db.setTransactionSuccessful() }finally { db.endTransaction() }
  28. { Extension Function Expression } db.inTransaction { delete("tableName","firstName =?", arrayOf("Jake"))

    }
  29. { Extension Function Expression } fun SQLiteDatabase.inTransaction(func: () -> Unit)

    { beginTransaction() try { func() setTransactionSuccessful() }finally { endTransaction() } } db.inTransaction { db.delete("tableName","firstName =?", arrayOf("Jake")) }
  30. { Extension Function Expression } fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit)

    { beginTransaction() try { func() setTransactionSuccessful() }finally { endTransaction() } } db.inTransaction { delete("tableName","firstName =?", arrayOf("Jake")) }
  31. { Kotlin in Android } // in java Button button

    = (Button) findViewById(R.id.my_button_id); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show(); } }); // in kotlin val button = findViewById(R.id.my_button_id) as Button button.setOnClickListener { toast("clicked") }
  32. { Kotlin in Android } // JAVA button.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

    @Override public void onGlobalLayout() { button.getViewTreeObserver().removeOnGlobalLayoutListener(this); Toast.makeText(Main2Activity.this, button.getHeight() +"", Toast.LENGTH_SHORT).show(); } }); kotlin any_type_view.afterMeasured { toast(any_type_view.height.toString()) }
  33. { Extension Function Expression } inline fun View.afterMeasured(crossinline f: View.()

    -> Unit) { viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { if (measuredWidth > 0 && measuredHeight > 0) { viewTreeObserver.removeOnGlobalLayoutListener(this) f() } } }) }
  34. { Kotlin in Android } // in java button.setOnClickListener(new View.OnClickListener()

    { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show(); } }); // in kotlin button.setOnClickListener { toast("clicked") }
  35. { Kotlin in Android }. no more findViewById Syntetic import

    apply plugin: 'kotlin-android-extensions' my_button_id.setOnClickListener { } my_text_view_id.text = "some text" <Button android:id="@+id/my_button_id" android:layout_width="match_parent" android:layout_height="50dp" /> <TextView android:id="@+id/my_text_view_id" android:layout_width="match_parent" android:layout_height="wrap_content" />
  36. { Kotlin in Android }.Anko library

  37. { Kotlin in Android }.Anko library async() { // Do

    something in a secondary thread uiThread { // Back to the main thread } }
  38. { Performance } ???

  39. { As fast as Java } thanks ;)

  40. https://kotlinlang.org/docs/reference/ http://antonioleiva.com/kotlin/ https://medium.com/keepsafe-engineering/kotlin-vs-java-compilation-speed-e6c174b39b5d#.8w0o4sh91

  41. with kotlin you get • lambdas • default methods •

    method references • extension lambdas • nullable types • null safety • inlined methods (which reduce the cost of lambdas immensely) • extension methods • improved type inference • operator overloading (limited) • infix methods • reified generics for methods • data classes • property delegation • interface delegation