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

Advancing Android Development with the Kotlin L...

Jake Wharton
November 06, 2015

Advancing Android Development with the Kotlin Language (Øredev 2015)

Using Kotlin for Android development has grown in popularity over the last year. Even to those who are not currently using it, the value proposition of the language immediately resonates. There already are a lot of introductory talks to the language and its extensions for use on Android. This talk will cover advancing the usage and design patterns of the language for Android development to solve larger problems. While the content is targeted at mobile development, there will be value for all Java developers interested in Kotlin.

Prior knowledge or use of Kotlin is not required to attend this talk. Some concepts of the language will be used without introduction but they are intuitive and/or quickly learned. Even if you don't fully understand every language concept on which each example is built, the resulting functionality will be clear.

Video: https://vimeo.com/144877458

Jake Wharton

November 06, 2015
Tweet

More Decks by Jake Wharton

Other Decks in Programming

Transcript

  1. Why do we need advancing? • Stuck on Java 6(.5)ish

    • No javax.time • No streams
  2. Why do we need advancing? • Stuck on Java 6(.5)ish

    • No javax.time • No streams • No lambdas, method refs, non-capturing anon class
  3. Why do we need advancing? • Stuck on Java 6(.5)ish

    • No javax.time • No streams • No lambdas, method refs, non-capturing anon class • No try-with-resources
  4. Why do we need advancing? • Stuck on Java 6(.5)ish

    • No javax.time Use ThreeTenBP / ThreeTenABP • No streams • No lambdas, method refs, non-capturing anon class • No try-with-resources
  5. Why do we need advancing? • Stuck on Java 6(.5)ish

    • No javax.time Use ThreeTenBP / ThreeTenABP • No streams Use backport or RxJava • No lambdas, method refs, non-capturing anon class • No try-with-resources
  6. Why do we need advancing? • Stuck on Java 6(.5)ish

    • No javax.time Use ThreeTenBP / ThreeTenABP • No streams Use backport or RxJava • No lambdas, method refs, non-capturing anon class Use Retrolambda • No try-with-resources
  7. Why do we need advancing? • Stuck on Java 6(.5)ish

    • No javax.time Use ThreeTenBP / ThreeTenABP • No streams Use backport or RxJava • No lambdas, method refs, non-capturing anon class Use Retrolambda • No try-with-resources minSdkVersion=19 or Retrolambda
  8. Why do we need advancing? • Stuck on Java 6(.5)ish

    • Java language restrictions and problems
  9. Why do we need advancing? • Java language restrictions and

    problems • Inability to add methods to platform types
  10. Why do we need advancing? • Java language restrictions and

    problems • Inability to add methods to platform types ("Util" hell)
  11. Why do we need advancing? • Java language restrictions and

    problems • Inability to add methods to platform types ("Util" hell) • Nullability problems
  12. Why do we need advancing? • Java language restrictions and

    problems • Inability to add methods to platform types ("Util" hell) • Nullability problems • General verbosity of common idioms
  13. Why do we need advancing? • Stuck on Java 6(.5)ish

    • Java language restrictions and problems
  14. Why do we need advancing? • Stuck on Java 6(.5)ish

    • Java language restrictions and problems • Android API design problems
  15. Why do we need advancing? • Android API design problems

    • Inheritance party • Nullability everywhere
  16. Why do we need advancing? • Android API design problems

    • Inheritance party • Nullability everywhere • Ceremony of APIs
  17. Why do we need advancing? • Stuck on Java 6(.5)ish

    • Java language restrictions and problems • Android API design problems
  18. Kotlin Statically typed programming language for the JVM, Android and

    the browser 100% interoperable with Java™
  19. Extension Functions static boolean IsTuesday(this DateTime date) {
 return date.DayOfWeek

    == DayOfWeek.Tuesday;
 } boolean tuesday = date.IsTuesday();
  20. Extension Functions // com/example/util/DateExtensions.kt fun Date.isTuesday() = day == 2

    // com/example/TuesdayActivity.kt val tuesday = date.isTuesday();
  21. Extension Functions // com/example/util/DateExtensions.kt fun Date.isTuesday() = day == 2

    // com/example/TuesdayActivity.kt val tuesday = date.isTuesday();
  22. Extension Functions // com/example/util/DateExtensions.kt fun Date.isTuesday() = day == 2

    // com/example/TuesdayActivity.kt import com.example.util.isTuesday val tuesday = date.isTuesday();
  23. Extension Functions // com/example/util/DateExtensions.kt fun Date.isTuesday() = day == 2

    final static isTuesday(Ljava/util/Date;)Z L0 ALOAD 0 INVOKEVIRTUAL java/util/Date.getDay ()I ICONST_2 IF_ICMPNE L1 ICONST_1 GOTO L2 L1 ICONST_0 L2 IRETURN
  24. Extension Functions // com/example/util/DateExtensions.kt fun Date.isTuesday() = day == 2

    static boolean isTuesday(Date date) {
 return date.getDay() == 2;
 }X
  25. Extension Functions // com/example/util/DateExtensions.kt fun Date.isTuesday() = day == 2

    @file:JvmName("DateUtils") // com/example/util/DateExtensionsKt.java static boolean isTuesday(Date date) {
 return date.getDay() == 2;
 }X
  26. Extension Functions // com/example/util/DateExtensions.kt fun Date.isTuesday() = day == 2

    @file:JvmName("DateUtils") // com/example/util/DateUtils.java static boolean isTuesday(Date date) {
 return date.getDay() == 2;
 }X
  27. Extension Functions fun Date.getDay() = 2 fun View.isAttachedToWindow() = if

    (Build.VERSION.SDK_INT < 19) ViewCompat.isAttachedToWindow(this) else super.isAttachedToWindow()
  28. Extension Functions fun Date.getDay() = 2 fun View.isAttachedToWindowCompat() = if

    (Build.VERSION.SDK_INT < 19) ViewCompat.isAttachedToWindow(this) else isAttachedToWindow()
  29. Extension Functions fun TextView.setTextSize(size: Float, unit: SizeUnit) {
 setTextSize(unit.toPixels(size, getContext()))


    } void setTextSize(float size) void setTextSize(int unit, float size) enum class SizeUnit {
 DP {
 override fun toPixels(context: Context) = // ...
 },
 SP {
 override fun toPixels(context: Context) = // ...
 };
 
 abstract fun toPixels(context: Context): Int
 }
  30. Extension Functions String firstName1= null;
 int firstNameColumn = cursor.getColumnIndexOrThrow("first_name");
 if

    (!cursor.isNull(firstNameColumn)) {
 firstName3=2cursor.getString(firstNameColumn);
 }
  31. Extension Functions String firstName1= null;
 int firstNameColumn = cursor.getColumnIndexOrThrow("first_name");
 if

    (!cursor.isNull(firstNameColumn)) {
 firstName3=2cursor.getString(firstNameColumn);
 } fun Cursor.getStringOrNull(columnName: String): String? {
 val index = getColumnIndexOrThrow(columnName)
 return if (isNull(index)) null else getString(index)
 }X
 fun Cursor.getString(columnName: String): String = getStringOrNull(columnName)!!
  32. Extension Functions fun Cursor.getStringOrNull(columnName: String): String? {
 val index =

    getColumnIndexOrThrow(columnName)
 return if (isNull(index)) null else getString(index)
 }X
 fun Cursor.getString(columnName: String): String = getStringOrNull(columnName)!!
  33. Extension Functions fun Cursor.getStringOrNull(columnName: String): String? {
 val index =

    getColumnIndexOrThrow(columnName)
 return if (isNull(index)) null else getString(index)
 }X
 fun Cursor.getString(columnName: String): String = getStringOrNull(columnName)!! val firstName = cursor.getStringOrNull("first_name")
  34. Extension Functions fun Cursor.getStringOrNull(columnName: String): String? {
 val index =

    getColumnIndexOrThrow(columnName)
 return if (isNull(index)) null else getString(index)
 }X
 fun Cursor.getString(columnName: String): String = getStringOrNull(columnName)!! val firstName = cursor.getStringOrNull("first_name")
  35. Extension Functions fun Cursor.getStringOrNull(columnName: String): String? {
 val index =

    getColumnIndexOrThrow(columnName)
 return if (isNull(index)) null else getString(index)
 }X
 fun Cursor.getString(columnName: String): String = getStringOrNull(columnName)!! val firstName = cursor.getStringOrNull("first_name")
  36. Extension Functions fun Cursor.getStringOrNull(columnName: String): String? {
 val index =

    getColumnIndexOrThrow(columnName)
 return if (isNull(index)) null else getString(index)
 }X
 fun Cursor.getString(columnName: String): String = getStringOrNull(columnName)!! val firstName = cursor.getStringOrNull("first_name")
  37. Function Expressions { x, y -> x + y }

    { x: Int, y: Int -> x + y } { it.toString() } { x, y -> x + y } { x: Int, y: Int -> x + y }
  38. Function Expressions { x, y -> x + y }

    { x: Int, y: Int -> x + y } val sum = { x: Int, y: Int -> x + y } val sum: (Int, Int) -> Int = { x, y -> x + y } { it.toString() }
  39. Function Expressions { !it.isEmpty() } { it.length() > 4 }

    { it.matches("\d{4}") } { luhnCheck(it) }
  40. Function Expressions val notEmpty: (String) -> Boolean { !it.isEmpty() }

    val atLeastFour: (String) -> Boolean { it.length() > 4 } val fourDigits: (String) -> Boolean { it.matches("\d{4}") } val validCreditCard: (String) -> Boolean { luhnCheck(it) }
  41. Higher-Order Functions fun apply(one: Int, two: Int, func: (Int, Int)

    -> Int): Int {
 return func(one, two)
 }
  42. Higher-Order Functions fun apply(one: Int, two: Int, func: (Int, Int)

    -> Int): Int {
 return func(one, two)
 } val sum = apply(1, 2, { x, y -> x + y })
  43. Higher-Order Functions fun apply(one: Int, two: Int, func: (Int, Int)

    -> Int): Int {
 return func(one, two)
 }X val sum = apply(1, 2, { x, y -> x + y } val difference = apply(1, 2, { x, y -> x - y } ) )
  44. Higher-Order Functions fun apply(one: Int, two: Int, func: (Int, Int)

    -> Int): Int {
 return func(one, two)
 }X val sum = apply(1, 2) { x, y -> x + y }
 val difference = apply(1, 2) { x, y -> x - y }
  45. Higher-Order Functions fun apply(one: Int, two: Int, func: (Int, Int)

    -> Int): Int {
 return func(one, two)
 }X
  46. Higher-Order Functions fun Int.apply(other: Int, func: (Int, Int) -> Int):

    Int {
 return func(this, other)
 } val sum = 1.apply(2) { x, y -> x + y }
 val difference = 1.apply(2) { x, y -> x - y }
  47. Higher-Order Functions fun Int.apply(func: (Int) -> Int): Int {
 return

    func(this)
 }X val double = 1.apply { x -> x * 2 }
  48. Higher-Order Functions fun Int.apply(func: (Int) -> Int): Int {
 return

    func(this)
 }X val double = 1.apply { it * 2 }
  49. Higher-Order Functions fun <T> List<T>.filter(predicate: (T) -> Boolean): List<T> {


    val newList = ArrayList<T>()
 for (item in this) {
 }Y
 return newList
 }X
  50. Higher-Order Functions fun <T> List<T>.filter(predicate: (T) -> Boolean): List<T> {


    val newList = ArrayList<T>()
 for (item in this) {
 if (predicate(item)) {
 }Z
 }Y
 return newList
 }X
  51. Higher-Order Functions fun <T> List<T>.filter(predicate: (T) -> Boolean): List<T> {


    val newList = ArrayList<T>()
 for (item in this) {
 if (predicate(item)) {
 newList.add(item)
 }Z
 }Y
 return newList
 }X
  52. Higher-Order Functions fun <T> List<T>.filter(predicate: (T) -> Boolean): List<T> {


    val newList = ArrayList<T>()
 for (item in this) {
 if (predicate(item)) {
 newList.add(item)
 }
 }
 return newList
 } val names = listOf("Jake", "Jesse", "Matt", "Alec")
 val jakes = names.filter { it == "Jake" }

  53. Higher-Order Functions fun Any.lock(func: () -> Unit) {
 synchronized (this)

    { func()
 }
 } writeLock.lock { if (!isClosed) { closeWriter() isClosed = true } }
  54. Higher-Order Functions data class Lock<T>(private val obj: T) {
 public

    fun acquire(func: (T) -> Unit) {
 synchronized (obj) {
 func(obj)
 }
 }
 }
  55. Higher-Order Functions data class Lock<T>(private val obj: T) {
 public

    fun acquire(func: (T) -> Unit) {
 synchronized (obj) {
 func(obj)
 }
 }
 } val readerLock = Lock(JsonReader(stream))
  56. Higher-Order Functions data class Lock<T>(private val obj: T) {
 public

    fun acquire(func: (T) -> Unit) {
 synchronized (obj) {
 func(obj)
 }
 }
 } val readerLock = Lock(JsonReader(stream))
 
 // Later
 readerLock.acquire { 
 println(it.readString())
 }
  57. Higher-Order Functions val notEmpty: (String) -> Boolean { !it.isEmpty() }

    val atLeastFour: (String) -> Boolean { it.length() > 4 } val fourDigits: (String) -> Boolean { it.matches("\\d{4}") } val validCreditCard: (String) -> Boolean { luhnCheck(it) }
  58. Higher-Order Functions val notEmpty: (String) -> Boolean { !it.isEmpty() }

    val atLeastFour: (String) -> Boolean { it.length() > 4 } val fourDigits: (String) -> Boolean { it.matches("\\d{4}") } val validCreditCard: (String) -> Boolean { luhnCheck(it) } firstName.validateWith(notEmpty) lastName.validateWith(notEmpty) username.validateWith(atLeastFour) pin.validateWith(fourDigits) creditCard.validateWith(validCreditCard) { !it.isEmpty() }
  59. Higher-Order Functions firstName.validateWith { !it.isEmpty() } lastName.validateWith { !it.isEmpty() }

    username.validateWith { it.length() > 4 } pin.validateWith { it.matches("\d{4}") } creditCard.validateWith { luhnCheck(it) }
  60. Higher-Order Functions val notEmpty: (String) -> Boolean { !it.isEmpty() }

    firstName.validateWith(notEmpty) lastName.validateWith(notEmpty) username.validateWith { it.length() > 4 } pin.validateWith { it.matches("\d{4}") } creditCard.validateWith { luhnCheck(it) } { !it.isEmpty() }
  61. Extension Function Expressions • Extension Functions — Functions added to

    a type without modifying the original. • Function Expressions — Undeclared function bodies used an as expression (i.e., as data).
  62. Extension Function Expressions • Extension Functions — Functions added to

    a type without modifying the original. • Function Expressions — Undeclared function bodies used an as expression (i.e., as data). • Higher-Order Functions: A function which takes a function or returns a function.
  63. Extension Function Expressions db.beginTransaction();
 try {
 db.delete("users", "first_name = ?",

    new String[] { "Jake" });
 db.setTransactionSuccessful();
 } finally {
 db.endTransaction();
 }
  64. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: () -> Unit) {
 beginTransaction()


    try {
 func()
 setTransactionSuccessful()
 } finally {
 endTransaction()
 }
 }
  65. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: () -> Unit) {
 beginTransaction()


    try {
 func(
 setTransactionSuccessful()
 } finally {
 endTransaction()
 }Y
 }X db.inTransaction { 
 }X )
  66. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: () -> Unit) {
 beginTransaction()


    try {
 func(
 setTransactionSuccessful()
 } finally {
 endTransaction()
 }Y
 }X db.inTransaction { 
 db.delete("users", "first_name = ?", arrayOf("Jake"))
 }X )
  67. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: (SQLiteDatabase) -> Unit) {
 beginTransaction()


    try {
 func(
 setTransactionSuccessful()
 } finally {
 endTransaction()
 }Y
 }X db.inTransaction { 
 db.delete("users", "first_name = ?", arrayOf("Jake"))
 }X )
  68. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: (SQLiteDatabase) -> Unit) {
 beginTransaction()


    try {
 func(this
 setTransactionSuccessful()
 } finally {
 endTransaction()
 }Y
 }X db.inTransaction { 
 db.delete("users", "first_name = ?", arrayOf("Jake"))
 }X )
  69. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: (SQLiteDatabase) -> Unit) {
 beginTransaction()


    try {
 func(this
 setTransactionSuccessful()
 } finally {
 endTransaction()
 }Y
 }X db.inTransaction { 
 it.delete("users", "first_name = ?", arrayOf("Jake"))
 }X )
  70. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) {
 beginTransaction()


    try {
 func(this
 setTransactionSuccessful()
 } finally {
 endTransaction()
 }Y
 }X db.inTransaction { 
 it.delete("users", "first_name = ?", arrayOf("Jake"))
 }X )
  71. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) {
 beginTransaction()


    try {
 this.func(
 setTransactionSuccessful()
 } finally {
 endTransaction()
 }Y
 }X db.inTransaction { 
 it.delete("users", "first_name = ?", arrayOf("Jake"))
 }X )
  72. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) {
 beginTransaction()


    try {
 func(
 setTransactionSuccessful()
 } finally {
 endTransaction()
 }Y
 }X db.inTransaction { 
 it.delete("users", "first_name = ?", arrayOf("Jake"))
 }X )
  73. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) {
 beginTransaction()


    try {
 func()
 setTransactionSuccessful()
 } finally {
 endTransaction()
 }Y
 }X db.inTransaction { 
 delete("users", "first_name = ?", arrayOf("Jake"))
 }X
  74. Extension Function Expressions NEW MyClassKt$deleteUsers$1 DUP ALOAD 2 INVOKESPECIAL MyClassKt$deleteUsers$1.<init>

    (Ljava/lang/String;)V CHECKCAST kotlin/jvm/functions/Function1 INVOKESTATIC DbExtensionsKt.inTransaction (Landroid/database/sqlite/SQLiteDatabase;Lkotlin/jvm/functions/Function1;)V db.inTransaction { 
 delete("users", "first_name = ?", arrayOf("Jake"))
 }X
  75. Extension Function Expressions DbExtensions.inTransaction(db, new Function1<SQLiteDatabase, Unit>() {
 @Override public

    Unit invoke(SQLiteDatabase db) {
 db.delete("users", "first_name = ?", new String[] { "Jake "});
 return null;
 }
 }); db.inTransaction { 
 delete("users", "first_name = ?", arrayOf("Jake"))
 }X
  76. Extension Function Expressions fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) {
 beginTransaction()


    try {
 func()
 setTransactionSuccessful()
 } finally {
 endTransaction()
 }Y
 }X
  77. Extension Function Expressions inline fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit) {


    beginTransaction()
 try {
 func()
 setTransactionSuccessful()
 } finally {
 endTransaction()
 }Y
 }X
  78. Extension Function Expressions L6 ALOAD 2 INVOKEVIRTUAL com/example/SQLiteDatabase.beginTransaction ()V L0

    NOP L9 ALOAD 2 CHECKCAST com/example/SQLiteDatabase ASTORE 3 L10 ALOAD 3 LDC "users" LDC "first_name = ?" ICONST_1 ANEWARRAY java/lang/String DUP ICONST_0 LDC "Jake" AASTORE CHECKCAST [Ljava/lang/String; INVOKEVIRTUAL com/example/SQLiteDatabase.delete (Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V L11 L12 GETSTATIC kotlin/Unit.INSTANCE : Lkotlin/Unit; POP L13 ALOAD 2 INVOKEVIRTUAL com/example/SQLiteDatabase.setTransactionSuccessful ()V L1 ALOAD 2 INVOKEVIRTUAL com/example/SQLiteDatabase.endTransaction ()V L14 GOTO L15 L2 ASTORE 3 L3 ALOAD 2 INVOKEVIRTUAL com/example/SQLiteDatabase.endTransaction ()V
  79. Extension Function Expressions db.beginTransaction();
 try {
 db.delete("users", "first_name = ?",

    new String[] { "Jake "});
 db.setTransactionSuccessful();
 } finally {
 db.endTransaction();
 }X
  80. Extension Function Expressions db.beginTransaction();
 try {
 db.delete("users", "first_name = ?",

    new String[] { "Jake "});
 db.setTransactionSuccessful();
 } finally {
 db.endTransaction();
 }X db.inTransaction { 
 delete("users", "first_name = ?", arrayOf("Jake"))
 }X + inline fun =
  81. Extension Function Expressions inline fun notification(context: Context, func: Notification.Builder.() ->

    Unit): Notification {
 val builder = Notification.Builder(context)
 builder.func()
 return builder.build()
 }
  82. Extension Function Expressions inline fun notification(context: Context, func: Notification.Builder.() ->

    Unit): Notification {
 val builder = Notification.Builder(context)
 builder.func()
 return builder.build()
 } val n = notification(context) {
 setContentTitle("Hi")
 setSubText("Hello")
 }
  83. Extension Function Expressions verticalLayout {
 padding = dip(30)
 editText {


    hint = "Name"
 textSize = 24f
 }
 editText {
 hint = "Password"
 textSize = 24f
 }
 button("Login") {
 textSize = 26f
 }
 }