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

Kotlin - Turbinando o Desenvolvimento Android

Kotlin - Turbinando o Desenvolvimento Android

Apresentada no Google Launchpad Build Recife 2017

Rafael Toledo

August 12, 2017
Tweet

More Decks by Rafael Toledo

Other Decks in Programming

Transcript

  1. JETBRAINS INICIADA EM 2010 PELA é uma linguagem de programação

    segura e acessível além de ser muito pragmática
  2. O QUE É? •Estaticamente tipada •Inspirada por Java, Scala, C#,

    Groovy •Targets: •JVM / Android •JavaScript •Nativo
  3. BENEFÍCIOS • Familiaridade com C#, Java, JavaScript, facilitando a adoção

    • Interoperabilidade com a plataforma • Java - JVM • JavaScript • Nativo - Interoperabilidade com C
  4. CONVENÇÕES • Segue as convenções de código do Java •

    Tipos em caixa alta - MeuTipo • Métodos e Properties em caixa baixa camelCase • Ponto e vírgula opcional* • Pacotes seguem a notação reversa • Múltiplas classes por arquivo são permitidas • Pacotes não precisam seguir a estrutura de pastas
  5. FERRAMENTAL • JDK •Versão 6, 7, 8 e 9 •

    Compilador Kotlin • Editor ou IDE • IntelliJ IDEA, Android Studio, Netbeans, Eclipse
  6. DATA CLASSES public class User { private String name; private

    String email; public void setName(String name) { this.name = name; } public String getName() { return name; } }
  7. MÚLTIPLAS CLASSES POR ARQUIVO data class User(val name: String, val

    email: String) data class Order(val id: Int, val user: User) data class Address(val street: String)
  8. PROPERTIES var simple: Int? val inferredType = 1 val isEmpty:

    Boolean get() = this.size == 0 var stringValue: String get() = this.toString() set(value) { splitAndAssign(value) } var privateSetter: String = "a" private set var annotated: Any? = null @Inject set
  9. EXTENSÕES @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return

    new ViewHolder(LayoutInflater.from( parent.getContext()).inflate(R.layout.item_list, parent, false)); }
  10. EXTENSÕES fun ViewGroup.inflate(layoutRes: Int, attachToRoot: Boolean = false): View {

    return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot) }
  11. EXTENSÕES @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return

    new ViewHolder(LayoutInflater.from( parent.getContext()).inflate(R.layout.item_list, parent, false)); }
  12. EXTENSÕES override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return

    ViewHolder(parent.inflate(R.layout.item_list)) } parent.inflate(R.layout.item_list) parent.inflate(R.layout.item_list, false) // Mesma coisa parent.inflate(R.layout.item_list, true)
  13. SINGLETON public class Singleton { private static final Singleton INSTANCE

    = new Singleton(); public static Singleton getInstance() { return INSTANCE; } private Singleton() { } }
  14. LAMBDAS public interface Callback { void onFinish(Result result); } public

    void asyncRequest(Callback callback) { ... callback.onFinish(result); }
  15. LAMBDAS asyncRequest(new Callback() { @Override public void onFinish(Result result) {

    Log.i("Callback", "Result was " + result.status()); } });
  16. LAMBDAS asyncRequest(result -> Log.i("Callback", "Result was " + result.status())); //

    Depende de Retrolambda, Jack (plugin 2.x) ou plugin 3.+
  17. LAMBDAS fun asyncRequest(callback: (Result) -> Unit) { ... callback(result) }

    asyncRequest { result -> Log.i("Callback", "Result was ${result.status()}") }
  18. LAMBDAS fun asyncRequest(callback: (Result) -> Unit) { ... callback(result) }

    asyncRequest { Log.i("Callback", "Result was ${it.status()}") }
  19. LAMBDA - PARÂMETROS NÃO UTILIZADOS fun loadProduct(id: Int) { api.fetchProduct(id)

    { (_, name, date) -> title.text = name createdOn.text = date.format() } }
  20. TYPE ALIAS typealias Length = Double typealias Weight = Double

    typealias Action<T> = (T) -> Unit typealias Multimap<K, V> = Map<K, List<V>>
  21. DESESTRUTURANDO CLASSES data class User(val username: String, val email: String)

    fun printUserData() { val (username, email) = fetchUser() println("${username}: ${email}") }
  22. COROUTINES - EXPERIMENTAL • Código assíncrono com cara de síncrono

    • É basicamente uma "thread" (só que bem mais leve) que é pausada e retomada posteriormente "We think that now we have got a great design of coroutines for Kotlin, but we realize that it has not been battle-tested enough."
  23. COROUTINES fun someWork(): CompletableFuture<String> = ... fun moreWork() = async

    { println("Work started") val str = await(someWork()) println("Work completed") }
  24. COROUTINES fun someWork(): CompletableFuture<String> = ... // CompletableFuture = minSdkVersion

    24 fun moreWork() = async { println("Work started") val str = await(someWork()) println("Work completed") }
  25. COROUTINES fun someWork(): CompletableFuture<String> = ... // CompletableFuture = minSdkVersion

    24 fun moreWork() = async { println("Work started") val str = await(someWork()) println("Work completed") }
  26. ASSINCRONISMO E UI THREAD ... doAsync { val result =

    api.fetchData() // Sync call uiThread { textView.text = result.data } }
  27. ANDROID EXTENSIONS Adeus ao findViewById() import kotlinx.android.synthetic.main.activity_main.* ... override fun

    onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContextView(R.layout.activity_main) textView.setText("It's a kind of magic!") }
  28. REFERÊNCIAS & LINKS Blog Oficial blog.jetbrains.com/kotlin anko github.com/kotlin/anko Blog do

    Antonio Leiva antonioleiva.com Kotlin Koans kotlinlang.org/docs/tutorials/koans.html
  29. REFERÊNCIAS & LINKS Livro: Kotlin for Android Developers leanpub.com/kotlin-for-android-developers Livro:

    Kotlin in Action manning.com/books/kotlin-in-action Kotlin Sandbox github.com/rafaeltoledo/kotlin-sandbox