O slideshow foi denunciado.
Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.

A quick and fast intro to Kotlin

680 visualizações

Publicada em

This is a bit old (we prepared this slides one year ago, for an internal presentation), but we hope it could be useful.

Publicada em: Tecnologia
  • Seja o primeiro a comentar

  • Seja a primeira pessoa a gostar disto

A quick and fast intro to Kotlin

  1. 1. KOTLIN ● Primary target JVM ● Javascript ● Compiled in Java byte code ● Created for industry Core goals is 100% Java interoperability.
  2. 2. KOTLIN main features Concise Drastically reduce the amount of boilerplate code you need to write. Safe Avoid entire classes of errors such as null pointer exceptions. Interoperable Leverage existing frameworks and libraries of the JVM with 100% Java Interoperability.
  3. 3. data class Person( var name: String, var surname: String, var age: Int) Create a POJO with: ● Getters ● Setters ● equals() ● hashCode() ● toString() ● copy() Concise public class Person { final String firstName; final String lastName; public Person(...) { ... } // Getters ... // Hashcode / equals ... // Tostring ... // Egh... }
  4. 4. KOTLIN lambdas ● must always appear between curly brackets ● if there is a single parameter then it can be referred to by it Concise val list = (0..49).toList() val filtered = list .filter({ x -> x % 2 == 0 }) val list = (0..49).toList() val filtered = list .filter { it % 2 == 0 }
  5. 5. NULL safety // ERROR // OK
  6. 6. // OK // ERROR NULL safety
  7. 7. // ERROR NULL safety
  8. 8. // ERROR SAFE CALL NULL safety
  9. 9. Extend existing classes functionality Ability to extend a class with new functionality without having to inherit from the class ● does not modify classes ● are resolved statically
  10. 10. Extend existing classes functionality fun String.lastChar() = this.charAt(this.length() - 1) // this can be omitted fun String.lastChar() = charAt(length() - 1) fun use(){ Val c: Char = "abc".lastChar() }
  11. 11. Everything is an expression val max = if (a > b) a else b val hasPrefix = when(x) { is String -> x.startsWith("prefix") else -> false } when(x) { in 1..10 -> ... 102 -> ... else -> ... } boolean hasPrefix; if (x instanceof String) hasPrefix = x.startsWith("prefix"); else hasPrefix = false; switch (month) { case 1: ... break case 7: ... break default: ... }
  12. 12. Default Parameters fun foo( i :Int, s: String = "", b: Boolean = true) {} fun usage(){ foo( 1, b = false) }
  13. 13. for loop can iterate over any type that provides an iterator implementing next() and hasNext() for (item in collection) print(item) for ((index, value) in array.withIndex()) { println("the element at $index is $value") }
  14. 14. Collections ● Made easy ● distinguishes between immutable and mutable collections val numbers: MutableList = mutableListOf(1, 2, 3) val readOnlyNumbers: List = numbers numbers.add(4) println(readOnlyView) // prints "[1, 2, 3, 4]" readOnlyNumbers.clear() // -> does not compile
  15. 15. Java 6
  16. 16. // Using R.layout.activity_main from the main source set import kotlinx.android.synthetic.main.activity_main.* class MyActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView.setText("Hello, world!") } } public class MyActivity extends Activity() { @override void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = (TextView) findViewById(R.id.textView); textView.setText("Hello, world!"); } } Kotlin Android Extensions
  17. 17. Extension functions fun Fragment.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(getActivity(), message, duration).show() } fragment.toast("Hello world!")
  18. 18. Activities startActivity( intentFor< NewActivity > ("Answer" to 42) ) Intent intent = new Intent(this, NewActivity.class); intent.putExtra("Answer", 42); startActivity(intent);
  19. 19. Functional support (Lambdas) view.setOnClickListener { toast("Hello world!") } View view = (View) findViewById(R.id.view); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(this, "asdf", Toast.LENGTH_LONG) .show(); } });
  20. 20. Dynamic Layout scrollView { linearLayout(LinearLayout.VERTICAL) { val label = textView("?") button("Click me!") { label.setText("Clicked!") } editText("Edit me!") // codice koltin // ... } }.style(...) ? Click me! Edit me!
  21. 21. Easily mixed with Java ● Do not have to convert everything at once ● You can convert little portions ● Write kotlin code over the existing Java code Everything still works
  22. 22. Kotlin costs nothing to adopt ● It’s open source ● There’s a high quality, one-click Java to Kotlin converter tool ● Can use all existing Java frameworks and libraries ● It integrates with Maven, Gradle and other build systems. ● Great for Android, compiles for java 6 byte code ● Very small runtime library 924 KB
  23. 23. Kotlin usefull links ● A very well done documentation : Tutorial, Videos ● Kotlin Koans online ● Constantly updating in Github, kotlin-projects ● Talks: Kotlin in Action, Kotlin on Android
  24. 24. What Java has that Kotlin does not https://kotlinlang.org/docs/reference/comparison-to-java.html
  25. 25. Primitive Types Everything is an object we can call member functions and properties on any variable. What Java has that Kotlin does not val a: Int? = 1 val b: Long? = a print(a == b)
  26. 26. Primitive Types Everything is an object we can call member functions and properties on any variable. What Java has that Kotlin does not val a: Int? = 1 val b: Long? = a print(a == b) // FALSE //
  27. 27. Primitive Types Everything is an object we can call member functions and properties on any variable. What Java has that Kotlin does not val b: Byte = 1 val i: Int = b val i: Int = b.toInt() val a: Int? = 1 val b: Long? = a print(a == b) // FALSE //
  28. 28. Primitive Types Everything is an object we can call member functions and properties on any variable. What Java has that Kotlin does not val b: Byte = 1 val i: Int = b // ERROR // val i: Int = b.toInt() // OK // val a: Int? = 1 val b: Long? = a print(a == b) // FALSE //
  29. 29. Static Members class MyClass { companion object Factory { fun create(): MyClass = MyClass() } } val instance = MyClass.create() What Java has that Kotlin does not Singleton object MyClass { // .... }
  30. 30. Gradle Goes Kotlin https://kotlinlang.org/docs/reference/using-gradle.html
  31. 31. Thank You Erinda Jaupaj @ErindaJaupi

×