$30 off During Our Annual Pro Sale. View details »

Dont worry - switch to Kotlin

sergbek
March 13, 2017

Dont worry - switch to Kotlin

sergbek

March 13, 2017
Tweet

Other Decks in Education

Transcript

  1. Kotlin

  2. Why … ? - “To invent the wheel” - Marketing

    - Сuriosity - “I do not like”
  3. Android 1.0 (Apple Pie) - 2008 year - java 6

  4. Android 6.0 - 2015 year - java 6* *with pieces

    of java 7
  5. Android 7.0 JAVA 8

  6. Lambdas

  7. Java 6/7 and

  8. What's wrong with java?

  9. Create class Person ID + First name + Last name

    +
  10. Create class person

  11. None
  12. None
  13. None
  14. None
  15. Statically typed programming language for the JVM. Android and the

    browser 100% interoperable with Java
  16. None
  17. What is the difference between Kotlin and Java?

  18. KOTLIN CAT JAVA CAT

  19. None
  20. Why do we need Kotlin? • Stuck on java 6

    (7) ◦ No streams ◦ No try-with-resources ◦ No lambdas, methods refs -> Use RxJava -> Use Retrolambda -> minSdkVersion = 19 or Retrolambda • Java language problems ◦ “Util Hell” ◦ Nullability problems ◦ Mutability problems ◦ General verbosity of common idioms
  21. Syntax Crash Course

  22. Syntax Crash Course

  23. Syntax Crash Course

  24. Syntax Crash Course

  25. Kotlin Features String templates Properties Lambdas Inline functions Data class

    Smart cast Null safety Default values for function parameters Lazy property Extension Functions Equals Single-expression functions When expression let, apply, use, with Collections Kotlin Android Extensions Plugin Anko
  26. String templates

  27. String templates >

  28. Properties

  29. Properties

  30. Extension Functions What it does ? How?

  31. Extension Functions fun showToast(context: Context, @StringRes idRes: Int){ Toast.makeText(context, idRes,

    Toast.LENGTH_LONG).show() } class MainActivity: AppCompatActivity() { fun showInfo() { showToast(this, R.string.error_network) } }
  32. Extension Functions

  33. Extension Functions fun Context.showToast(@StringRes idRes: Int){ Toast.makeText(this, idRes, Toast.LENGTH_LONG).show() }

    class MainActivity: AppCompatActivity() { fun showInfo() { // or this.showToast(R.string.error_network) showToast(R.string.error_network) } }
  34. Extension Functions fun Float.dpToPx(): Int { val metrics = Resources.getSystem().displayMetrics

    val px = this * (metrics.densityDpi / 160f) return Math.round(px) } fun Int.pxToDp(): Int { val metrics = Resources.getSystem().displayMetrics val dp = this / (metrics.densityDpi / 160f) return Math.round(dp) }
  35. Lambdas Function that is not declared, but passed immediately as

    an expression.
  36. Lambdas

  37. Lambdas

  38. Lambdas

  39. Lambdas

  40. Lambdas

  41. Lambdas Expensive operation

  42. Lambdas invoke lambda

  43. Lambdas invoke lambda

  44. Lambdas and Closures

  45. Inline functions

  46. Creating a new lambda reference

  47. Inline functions

  48. Data class What it does ? Nothing. Just hold data

    What it provides ? - getters, setters - equals() / hashCode() - toString - copy() function
  49. Data class > Person(id=1, firstName=Bogdan, lastName=Salo)

  50. Smart cast

  51. Smart cast

  52. Smart cast

  53. Smart cast smart cast

  54. Null safety Kotlin’s type system is aimed to eliminate NullPointerException’s

    from our code.
  55. Null safety

  56. Null safety compilation error

  57. Null safety

  58. Null safety compilation error

  59. Null safety

  60. Null safety

  61. Null safety

  62. Null safety

  63. Null safety

  64. Null safety

  65. Default values for function parameters Function parameters can have default

    values, which are used when a corresponding argument is omitted. This allows for a reduced number of overloads compared to other languages.
  66. Default values for function parameters

  67. Default values for function parameters

  68. Default values for function parameters

  69. Default values for function parameters

  70. Lazy property Value gets computed only upon first access.

  71. Lazy property val preference = getSharedPreferences("pref") override fun onCreate(savedInstanceState: Bundle?)

    { super.onCreate(savedInstanceState) val username = preference.getString("username") } crash, require context
  72. Lazy property val preference = getSharedPreferences("pref") override fun onCreate(savedInstanceState: Bundle?)

    { super.onCreate(savedInstanceState) val username = preference.getString("username") }
  73. Lazy property val preference by lazy { getSharedPreferences("pref") } override

    fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val username = preference.getString("username") }
  74. Lazy property val validator: Validator by lazy { Validator(this) }

    button1.click { validator.validate() } button2.click { validator.validate()}
  75. Single-expression functions

  76. Single-expression functions

  77. Single-expression functions return type is optional

  78. Single-expression functions

  79. When expression

  80. When expression

  81. When expression can be anything

  82. When expression can be anything

  83. When expression

  84. When expression

  85. When expression

  86. When expression

  87. let, apply, use, with Higher-order functions - function that takes

    functions as parameters, or returns a function.
  88. let (scope function)

  89. let Preferences.getUser().let { showUserName(it.name) showUserEmail(it.email) }

  90. let supportActionBar?.let { it.setTitle(R.string.basket) it.setDisplayShowTitleEnabled(true) it.setHomeButtonEnabled(true) it.setDisplayHomeAsUpEnabled(true) }

  91. with

  92. with recyclerView.setHasFixedSize(true) recyclerView.addItemDecoration(createDecorator()) recyclerView.layoutManager = LinearLayoutManager(context) recyclerView.adapter = myAdapter

  93. with with (recyclerView) { recyclerView.setHasFixedSize(true) recyclerView.addItemDecoration(createDecorator()) recyclerView.layoutManager = LinearLayoutManager(context) recyclerView.adapter

    = myAdapter }
  94. with with (recyclerView) { recyclerView.setHasFixedSize(true) recyclerView.addItemDecoration(createDecorator()) recyclerView.layoutManager = LinearLayoutManager(context) recyclerView.adapter

    = myAdapter } not need
  95. with with (recyclerView) { setHasFixedSize(true) addItemDecoration(createDecorator()) layoutManager = LinearLayoutManager(context) adapter

    = myAdapter }
  96. with with (recyclerView) { setHasFixedSize(true) addItemDecoration(createDecorator()) layoutManager = LinearLayoutManager(context) adapter

    = myAdapter }
  97. with inline fun <T: BaseInteractor> withInteractor(receiver: T, block: T.() ->

    Unit) = receiver.block() withInteractor(loginInteractor) { loginCustomer(password, username) .execute({ onLoginSuccess(it) }, { ErrorHandler.onError(router, it) }) }
  98. apply

  99. apply SomeModel() .apply { isHeader = true } .apply {

    nameHeader = "I`m header" }
  100. use (try with resources function)

  101. use (try with resources function) fun countUsers(): Long { val

    database = openDatabase() val result = database.count("users") database.close() return result } need to close
  102. use (try with resources function) fun countUsers(): Long { val

    database = openDatabase() val result = database.count("users") database.close() return result } fun countUsers() = openDatabase().use { it.count("users") } need to close
  103. use (try with resources function) fun countUsers(): Long { val

    database = openDatabase() val result = database.count("users") database.close() return result } fun countUsers() = openDatabase().use { it.count("users") } automatically close database
  104. Collections

  105. Collections no such method

  106. Collections > [1, null, 2, null, 3, 4, 5, 6,

    7, 8, 9]
  107. Collections > [1, 2, 3, 4, 5, 6, 7, 8,

    9]
  108. Collections > [2, 4, 6, 8]

  109. Collections > [8, 6, 4, 2]

  110. Collections enum

  111. Collections enum

  112. Collections getOrElse() find() filter() filterNot() filterNotNull() flatMap() take() takeLast() sortBy()

    sumBy() sortByDescending() groupBy() map() mapNotNull() all() any() maxBy() minBy() minWith() zip() ….
  113. findViewById()

  114. Kotlin Android Extensions Plugin What it does ? How?

  115. Kotlin Android Extensions Plugin buildscript { dependencies { classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"

    } } apply plugin: 'kotlin-android-extensions'
  116. Kotlin Android Extensions Plugin // R.layout.activity_order_info import kotlinx.android.synthetic.main.activity_order_info.*

  117. Kotlin Android Extensions Plugin // R.layout.activity_order_info import kotlinx.android.synthetic.main.activity_order_info.* public class

    OrderInfoActivity: AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_order_info) txtTitle.text = "Hello, Kotlin!" btnHello.setOnClickListener {...} } }
  118. Kotlin Android Extensions Plugin // R.layout.activity_order_info import kotlinx.android.synthetic.main.activity_order_info.* public class

    OrderInfoActivity: AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_order_info) txtTitle.text = "Hello, Kotlin!" btnHello.setOnClickListener {...} } } <Button android:id="@+id/btnHello" android:layout_width="match_parent" android:layout_height="wrap_content"/>
  119. Anko What it does ?

  120. Intents

  121. Intents

  122. Some useful intents

  123. Services

  124. Services

  125. Async

  126. Async

  127. Compatibility with Java - 100% - Kotlin can call any

    method from Java - Java can call any function from Kotlin - Add Kotlin to an existing Java project is very simple
  128. Thank you for attention!