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

Introdução ao Kotlin

Introdução ao Kotlin

Slides usados no 1º Android Day Aracaju para apresentar uma introdução a linguagem Kotlin

Avatar for Thiago Santos

Thiago Santos

June 03, 2017
Tweet

More Decks by Thiago Santos

Other Decks in Programming

Transcript

  1. • Não tem try-with-resources (Java < 7); • Falta de

    expressões lambda (Java < 8); • Sem Stream API (Java < 8); • Caused by: java.lang.NullPointerException: Deveria ter mais item nessa lista. at Slide2.java:4 (Java > 0) Problemas com Java
  2. • Apache Commons ~480kb; • Google Guava ~2477kb; • Retrolambda

    ~232kb; • RxJava e RxAndroid ~1973kb; • Um Hello World com ~5.100kb Contornando os Problemas
  3. “Kotlin é uma linguagem estaticamente tipada que tem como foco

    a JVM, Android, JavaScript e, recentemente, Nativo, desenvolvida e mantida pela JetBrains.”
  4. fun sum(a: Int, b: Int): Int { return a +

    b } public int sum(int a, int b) { return a + b; } Kotlin function JAVA method Public is default fun sum(a: Int, b: Int) = a + b Type inferred
  5. val a = 1 val b = 2 val sum

    = sum(a, b) println(“a + b = ${sum}”) println(“a + b = $sum”) println(“a + b = ${a + b}”) println(“a + b = ${sum(a, b)}”) int a = 1; int b = 2; int sum = sum(a, b); sout(“a + b = ” + sum); souf(“a + b = %d\n”, sum); String.format(“a + b = %d\n”, sum); Kotlin templates JAVA templates Read-only
  6. fun Date.addDays(days: Int = 1): Date { val calendar =

    Calendar.getInstance() calendar.time = this calendar.add(Calendar.DAY_OF_MONTH, days) return calendar.time } Receiver type Optional default value setTime() getTime() The receiver val date = Date() val m1 = date.addDays() // add 1 day val m30 = date.addDays(30) // add 30 days val m20 = date.addDays(days = 20) // add 20 days No new Named arguments
  7. infix fun Date.addDays(days: Int): Date { val calendar = Calendar.getInstance()

    calendar.time = this calendar.add(Calendar.DAY_OF_MONTH, days) return calendar.time } No default value val date = Date() val m1 = date.addDays(1) // add 1 day val m20 = date.addDays(days = 20) // add 20 days val m30 = date addDays 30 // add 30 days Call using spaces
  8. operator fun Date.plus(days: Int): Date { val calendar = Calendar.getInstance()

    calendar.time = this calendar.add(Calendar.DAY_OF_MONTH, days) return calendar.time } val date = Date() val m20 = date.plus(20) // add 20 days val m30 = date + 30 // add 30 days Using plus operator No default value
  9. for (i in 2000..2017) { println(i) } foreach Iterator check

    Range operator val years = (2017 downTo 2000) Infix function val worldCups = (1950..2017 step 4) Infix function val alphabetic = (‘A’..‘Z’) val yearsList = ((currentYear - 10)..(currentYear + 10)).toList()
  10. var name: String = “Thiago” name = null // Compilation

    error Mutable override fun equals(other: Any?): Boolean { if (other is User) { return this.id == other.id } return false } var name: String? = “Thiago” name = null // I love null val nullOrLength: Int? = name?.length Safe call Elvis operator val neverNull: Int = name?.length ?: -1 Smart cast Modificador Object
  11. • Throw NullPointerException(); • Uso do operador !! (val throwOrLength:

    Int = name!!.length) • Códigos java sem tratamento; • Inconsistência de dados. Formas de obter NullPointerException
  12. class User constructor (val id: Int, val name: String) public

    final Primary constructor data class User(val id: Int, val name: String) hashCode, equals, toString & copy data class User(val id: Int = 0, val name: String = “”) Default arguments open class Person(val id: Int, val name: String) class User(id: Int, name: String) : Person(id, name) No final No val/var extends/implements
  13. val (id, name) = mDataClassUserInstance Component operator data class User

    for ((key, value) in mMap) { println(“$key -> $value”) } class User(val id: Int, val name: String) { operator fun component1(): Int { return id } operator fun component2(): String { return name } } Manual implementation
  14. val mTextView: TextView by lazy { findViewById(R.id.textView) as TextView }

    Manual cast class User(val map: Map<String, Any?>) { val id: Int? by map val name: String? by map } val user = User(mapOf( Pair(“id”, 1), “name” to “Thiago” )) Collection utility Pair infix operator Key, value representation
  15. val list = listOf(1,2,3,4,5) .filter(fun(num) = num > 3) .reduce(fun(a,b)

    = a + b) Anonymous function Lambda expression view.setOnClickListener { Log.d(TAG, “View id: ${it.id}”) } val list = arrayListOf(1,2,3,4,5) .filter { num -> num > 3 } .reduce { a, b -> a + b } Implicit name
  16. inline 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 } Higher-Order Modifier Generics val list = arrayListOf(1,2,3,4,5).filter { it > 3 } println(list) // [4, 5] Extension function
  17. inline fun SQLiteDatabase.inTransaction( operation: SQLiteDatabase.() -> Unit): Unit { this.beginTransaction()

    try { this.operation() this.setTransactionSuccessful() } finally { this.endTransaction() } } myDbInstance.inTransaction { delete(“tb_user”, “id = ?”, arrayOf(1)) }
  18. inline fun SharedPreferences.edit( operation: SharedPreferences.Editor.() -> Unit): Unit { val

    editor = edit() editor.operation() editor.apply() } val user = User(1, “programadorthi”, true) mSPInstance.save(user) fun SharedPreferences.save(user: User): Unit { edit { putInt(“user_id”, user.id) putString(“user_name”, user.username) putBoolean(“stay_signed_in”, user.staySignedIn) } }
  19. mButtonSearch?.let { it.setOnClickListener { when { mViewFirstName.text.isBlank() -> toast(“Error message”)

    mViewLastName.text.isBlank() -> toast(“Error message”) mViewAge.text.toInt() in 1..18 -> toast(“too young”) mViewEmail !is TextView -> toast(“Wrong type”) else -> toast(“OK”) } } } Null safety call Standard library Instance of
  20. • Site - http://kotlinlang.org/ • Online IDE - https://try.kotlinlang.org •

    Jake Wharton - Android Development with Kotlin • Kotlin - https://developer.android.com/kotlin/index.html