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

Kotlin Codelabs GDG Mumbai (IO Extended 18)

Kotlin Codelabs GDG Mumbai (IO Extended 18)

I am @jayeshsolanki93 on Twitter.

Avatar for Jayesh

Jayesh

May 12, 2018

Other Decks in Programming

Transcript

  1. if

  2. // Kotlin val max = if (a > b) a

    else b // Java int max = a > b ? a : b;
  3. val max = if (a > b) { print("Max is

    a") a } else { print("Max is b") b } * else case is required when used as expression
  4. // Java switch (x) { case 1: System.out.println("x == 1");

    break; case 2: System.out.println("x == 2"); break; default: System.out.println("x is neither 1 nor 2"); } // Kotlin when (x) { 1 -> println("x == 1") 2 -> println("x == 2") else -> println("x is neither 1 nor 2") }
  5. // Java switch (x) { case 1: case 2: System.out.println("x

    == 1 or x == 2”); break; default: System.out.println("x is neither 1 nor 2"); } // Kotlin when (x) { 1..2 -> println("x == 1 or x == 2") else -> println("x is neither 1 nor 2") }
  6. when (obj) { 1 -> println("One") "Hello" -> println("Greeting") is

    Long -> println("Long") !is String -> println("Not a string") else -> println("Unknown") }
  7. override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.home ->

    // Open the drawer. R.id.search -> // Show search. R.id.settings -> // Go to settings. else -> super.onOptionsItemSelected(item) }
  8. let

  9. val charlie: Person? = null if (charlie != null) {

    // use the object } charlie?.let { // let reads only once }
  10. // Kotlin when (x) { is Int -> print(x *

    100) is String -> print("$x is a string") is Computer -> x.shutdown() } // Java if (x instanceof Integer) { System.out.println(((Integer)x) * 100); } else if (x instanceof String) { System.out.println(x + " is a string"); } else if (x instanceof Computer) { ((Computer) x).shutdown(); }
  11. Data classes •equals() / hashCode() •toString() •componentN() functions for destructuring

    declarations •copy() data class Person(val name: String, val age: Int)
  12. fun drawHRLine(character: Char = '=', length: Int = 10) {

    for (i in 1..length) { print(character) } } drawHRLine('*') drawHRLine() drawHRLine(12) // Compile Error! Cannot do this drawHRLine('=', 12) // Does not seem real nice drawHRLine(length = 12) // Named argument
  13. // Java public String foo(String name, int number, boolean toUpperCase)

    { return (toUpperCase ? name.toUpperCase() : name) + number; } public String foo(String name, int number) { return foo(name, number, false); } public String foo(String name, boolean toUpperCase) { return foo(name, 42, toUpperCase); } public String foo(String name) { return foo(name, 42); } // Kotlin fun foo(name: String, number: Int = 42, toUpperCase: Boolean = false): String { return (if (toUpperCase) name.toUpperCase() else name) + number }
  14. // Java public class Singleton { private static Singleton instance

    = null; private Singleton() { } private synchronized static void createInstance() { if (instance == null) { instance = new Singleton(); } } public static Singleton getInstance() { if (instance == null) createInstance(); return instance; } }
  15. data class Person( var name: String, var age: Int, var

    mobile: String = "", var email: String = "" ) Person(name = "Alice", age = 20).apply { mobile = "999999" email = "[email protected]" }
  16. val sum: (Int, Int) -> Int = { x, y

    -> x + y } val sum = { x: Int, y: Int -> x + y } val notEmpty: (TextView) -> Boolean = { it.text.isNotEmpty() } val notEmpty = { textView: TextView -> textView.text.isNotEmpty() } Lamda Expressions
  17. // Java (Anonymous Inner class) fab.setOnClickListener(new View.OnClickListener() { @Override public

    void onClick(View view) { doSomething(); } }); // Kotlin fab.setOnClickListener { doSomething() }
  18. data class Person( val id: String, var name: String, var

    age: Int ) val (id) = Person("jayesh26121993", "Jayesh", 24) id.getBirthDate() // Return 26121993 // Extension function. fun String.getBirthDate(): String { return substring(length - 8, length) }
  19. Extension functions • Are the new Util classes • Are

    not member functions • Do not modify the original class in any way • Are resolved at compile time by static type information • Are compiled to static functions in Java
  20. fun <T, R> Iterable<T>.map(predicate: (T) -> R): List<R> { val

    destination = ArrayList<R>() for (item in this) { destination.add(predicate(item)) } return destination } Higher Order Function val original = arrayListOf(2, 4, 6, 8) original.map { it + 2 } // 4, 6, 8, 10
  21. fun AppCompatActivity.setupActionBar(@IdRes toolbarId: Int, action: ActionBar.() -> Unit) { setSupportActionBar(findViewById(toolbarId))

    supportActionBar?.run { action() } } // Set up the toolbar. setupActionBar(R.id.toolbar) { setDisplayHomeAsUpEnabled(true) setDisplayShowHomeEnabled(true) setTitle(R.string.home_title) }
  22. private inline fun FragmentManager.transact( action: FragmentTransaction.() -> Unit) { beginTransaction().apply

    { action() }.commit() } fragmentManager.transact { replace(frameId, fragment) } fragmentManager.transact { add(fragment, tag) }
  23. KTX

  24. val string = buildSpannedString { append("no styling text") bold {

    append("bold") italic { append("bold and italic") } } inSpans(RelativeSizeSpan(2f), QuoteSpan()) { append("double sized quote text") } } Spanning with KTX extensions
  25. Features covered • Null safety • Data classes • Default

    and named arguments • Smart casts • Lamdas and Higher-Order functions • Extensions
  26. Not covered • Ranges • Exception handling • Visibility Modifiers

    • Nested/Sealed/Enum classes • Coroutines • Generics
  27. References • https://kotlinlang.org/docs/reference/ • https://try.kotlinlang.org/ • https://github.com/MindorksOpenSource/from-java-to-kotlin • https://android.jlelse.eu/switching-from-java-to-kotlin-5-exciting-features- for-android-developers-49ce712a546

    • http://www.baeldung.com/kotlin-when • https://twitter.com/AndroidDev • https://www.programiz.com/kotlin-programming/default-named-arguments • https://www.youtube.com/watch?v=5IOPd35j-ys