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

Kotlin for Android Developers (v2)

Kotlin for Android Developers (v2)

During the process of coding a Contacts App, we'll see some of the Kotlin features that will boost Android development, and how they compare with Java.

The complete code of the presentation can be found at: https://github.com/antoniolg/kontacts

Slides from talk at Codemotion 2015.

Antonio Leiva

November 27, 2015
Tweet

More Decks by Antonio Leiva

Other Decks in Programming

Transcript

  1. What is Kotlin? • JVM based • Object-oriented functional language

    • Created by JetBrains (IntelliJ, Android Studio) • Simple,lightweight, interoperable
  2. JAVA public class Contact {
 
 private final String name;


    private final String imageUrl;
 
 public Contact(String name, String imageUrl) {
 this.name = name;
 this.imageUrl = imageUrl;
 }
 
 public String getName() {
 return name;
 }
 
 public String getImageUrl() {
 return imageUrl;
 }
 }
  3. JAVA public class Contact {
 
 …
 
 public String

    toString() {
 return String.format("name: %s; imageUrl: %s", name, imageUrl);
 }
 
 @Override public boolean equals(Object o) {
 if (o instanceof Contact) {
 Contact c = (Contact) o;
 return name.equals(c.getName()) && imageUrl.equals(c.getImageUrl());
 } else {
 return false;
 }
 }
 }
  4. String templates KOTLIN override fun toString(): String {
 
 }

    
 return "name: $name; imageUrl: $imageUrl"

  5. Auto-Casting KOTLIN override fun equals(other: Any?) = when (other) {


    is Contact -> name == other.name 
 && imageUrl == other.imageUrl
 else -> false
 }
  6. Null safety KOTLIN var artist: Artist? = null
 artist.print() var

    artist: Artist? = null
 artist?.print() won´t compile will do nothing if (artist != null) {
 artist.print()
 } Smart cast var artist: Artist? = null
 artist!!.print() will crash
  7. View binding Java -> Butterknife Kotlin -> Property delegation val

    recyclerView by lazy { findViewById(R.id.recycler) as RecyclerView }
  8. View binding Java -> Butterknife Kotlin -> Property delegation val

    recyclerView by lazy { findViewById(R.id.recycler) as RecyclerView }
  9. Kotlin Android Extensions Direct access to XML views using its

    id as property name activity_main.xml <FrameLayout
 android:id="@+id/frameLayout"
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
 
 <android.support.v7.widget.RecyclerView
 android:id="@+id/recycler"
 android:layout_width="match_parent"
 android:layout_height="match_parent"/>
 
 </FrameLayout>
  10. Kotlin Android Extensions Import synthetic properties import kotlinx.android.synthetic.activity_main.* Use the

    properties override fun onCreate(savedInstanceState: Bundle?) {
 super<BaseActivity>.onCreate(savedInstanceState) setContentView(R.id.main)
 } recycler.layoutManager = GridLayoutManager(this, 2)
 recycler.adapter = ContactsAdapter(contacts)

  11. Kotlin Android Extensions Also works on views! import kotlinx.android.synthetic.view_item.view.* Use

    the properties class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
 
 fun bind(contact: Contact, listener: (Contact) -> Unit) {
 itemView.contactText.text = contact.name
 itemView.contactImage.loadUrl(contact.imageUrl)
 }
 }
  12. Asynchrony object: AsyncTask<Unit, Unit, List<Contact>>(){
 override fun doInBackground(vararg params: Unit?):

    List<Contact> {
 return GetContactsCommand().execute(this@MainActivity)
 }
 
 override fun onPostExecute(result: List<Contact>) {
 if (!isFinishing)
 recycler.adapter = ContactsAdapter(result) { navigateToDetail(it) };
 }
 }
  13. Anko • DSL to declare UIs in Kotlin verticalLayout {


    val name = editText()
 button("Say Hello") {
 onClick { toast("Hello, ${name.text}!") }
 }
 }
  14. Anko • DSL to declare UIs in Kotlin • Useful

    functions and properties context.layoutInflater context.notificationManager
 context.sensorManager
 context.vibrator toast(R.string.message)
 longToast("Wow, such a duration")
  15. Anko • DSL to declare UIs in Kotlin • Useful

    functions and properties • SQLite helpers
  16. Anko • DSL to declare UIs in Kotlin • Useful

    functions and properties • SQLite helpers • Easy asynchrony
  17. Navigate to Detail private fun navigateToDetail(contact: Contact) {
 
 }

    
 val intent = Intent(this, DetailActivity::class.java)
 intent.putExtra("name", contact.name)
 intent.putExtra("imageUrl", contact.imageUrl)
 startActivity(intent)

  18. Navigate (with Anko) private fun navigateToDetail(contact: Contact) {
 
 }

    
 startActivity<DetailActivity>("name" to contact.name,
 "imageUrl" to contact.imageUrl)

  19. return LayoutInflater.from(context) .inflate(layoutRes, this,
 } Extension functions fun ViewGroup.inflate(layoutRes: Int

    ): View { ) attachToRoot: Boolean = false , attachToRoot viewGroup.inflate(R.layout.view_item)
 viewGroup.inflate(R.layout.view_item, false)
 viewGroup.inflate(R.layout.view_item, true)
  20. Lambdas public interface Callback<T> {
 void invoke(T result);
 }
 


    public void asyncOperation(int value, Callback<Boolean> callback){
 ...
 callback.invoke(true);
 } JAVA asyncOperation(5, new Callback<Boolean>() {
 @Override public void invoke(Boolean result) {
 System.out.println("Result: " + result);
 }
 });
  21. Lambdas fun asyncOperation(value: Int, callback: (Boolean) -> Unit) {
 ...


    callback(true)
 } asyncOperation(5) { result ->
 println("result: $result")
 }
  22. Lambdas fun asyncOperation(value: Int, callback: (Boolean) -> Unit) {
 ...


    callback(true)
 } asyncOperation(5) { result ->
 println("result: $result")
 } asyncOperation(5) { println("result: $it") }
  23. Lambdas asyncOperation(5) { println("result: $it") } asyncOperation(5, new Callback<Boolean>() {


    @Override public void invoke(Boolean result) {
 System.out.println("Result: " + result);
 }
 });
  24. Lambdas recycler.adapter = ContactsAdapter(contacts) { navigateToDetail(it) } class ContactsAdapter(val contacts:

    List<Contact>, val listener: (Contact) -> Unit) itemView.setOnClickListener { listener(contact) }
  25. Collections • Iterable • Collection • List • Set •

    Map filter sort map zip dropWhile first firstOrNull last lastOrNull fold …
  26. Collections val contacts = ArrayList<Contact>()
 
 for (contact in parsedContacts)

    {
 if (contact.name != null && contact.image != null) {
 contacts.add(Contact(contact.name, contact.image))
 }
 }
 
 Collections.sort(contacts, { o1, o2 -> if (o1.name <= o2.name) -1 else 1 })
  27. Collections parsedContacts .filter { it.name != null && it.image !=

    null }
 .sortedBy { it.name }
 .map { Contact(it.name!!, it.image!!) }
  28. http://antonioleiva.com/book/ Kotlin for Android Developers • Create App from scratch

    • Step by step • Complete Kotlin coverage • Updated to latest version