1. 程式人生 > >How lambdas work in Kotlin. setOnClickListener transformation (KAD 18)

How lambdas work in Kotlin. setOnClickListener transformation (KAD 18)

Although I spoke a little about it in another article, I’d like to explain in depth how lambdas work in Kotlin, and how they transform the interfaces with a single method in lambdas when we  are working with Java libraries.

In particular I’m going to show you some examples on how to simplify the use of the Android Framework, and we’ll see the setOnClickListener

of the Android views in detail.

SetOnClickListener transformation

One of the features I like most about Kotlin is that it simplifies the work with the Android framework thanks to some conventions.

For example, the setOnClickListener function, which in Java is defined as:

123 publicvoidsetOnClickListener(OnClickListenerl){...}

When we use it in Kotlin, it corresponds to the following:

1 fun
setOnClickListener(l:(View)->Unit)

This saves us the need to have to create an anonymous implementation of the interface, greatly simplifying the initialization of UI components.

Want to learn Kotlin?

Check my free guide to create your first project in 15 minutes!

Using setOnclickListener. The original way

Following the above, we’ve already saved enough code. This is what we would have if we had to create an anonymous class of OnClickListener:

12345 view.setOnClickListener(object:View.OnClickListener{override fun onClick(v:View?){toast("Hello")}})

But you’ll see that the editor shows you a warning directly, and recommends using the lambda way.

This is the transformation you can do:

1 view.setOnClickListener({v->toast("Hello")})

Easier, right? But this can be simplified even more.

If the function’s last parameter is a function, it can go outside the parentheses

Therefore, we can extract the listener as follows:

1 view.setOnClickListener(){v->toast("Hello")}

If we had more parameters, the rest of the parameters would go inside the parentheses, even if these were functions. Only the last parameter can be extracted.

If a function has only one parameter, and this is a function, the parentheses can be deleted

Instead of having empty parentheses, we can better delete them:

1 view.setOnClickListener{v->toast("Hello")}

This comes great for building code blocks. In this way we can define DSLs that model our own language.

A very typical example is the Kotlin reference page, where they build a DSL to create HTML by code.

If you don’t use the parameter of a lambda, you can remove the left side of the function

This is true if you only have one parameter. The view (v) isn’t being used, so we can remove it:

1 view.setOnClickListener{toast("Hello")}

In addition, in functions that only receive a parameter, instead of defining the left side, we could use the reserved word it, saving some characters.

For example, if we used the view to pass it to another method:

1 view.setOnClickListener{v->doSomething(v)}

We have the option to simply use it:

1 view.setOnClickListener{doSomething(it)}

Your friends, the Lambdas

You see that the code difference is quite important. And not only for the characters you save (about 70%), but it greatly improves readability.

Instead of having to skip all the code that does nothing to find the useful part, we just write what really matters.

And like this, there are many other Kotlin features that allow huge boilerplate reduction.

If you want to learn a lot more about all this and get enough fluency to create your own Android Apps, I recommend you to get the free guide to learn how to build your first project, or just get the book and learn how to create a complete App from scratch.

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.

Shares

Like this:

Like Loading...

相關推薦

How lambdas work in Kotlin. setOnClickListener transformation (KAD 18)

Although I spoke a little about it in another article, I’d like to explain in depth how lambdas work in Kotlin, and how they transform the interfaces

Lambdas in Kotlin, and how they simplify Android development (KAD 07)

Lambdas are one of the most powerful tools in Kotlin, and in any other modern language, since it allows modelling functions in a much simpler way. Th

Reified Types in Kotlin: how to use the type within a function (KAD 14)

One of the limitations that most frustrates Java developers when using generics is not being able to use the type directly. Normally this is solved b

3D功能如何在PCL中工作(How 3D Features work in PCL)

本文件介紹了PCL中的三維特徵估計方法,並作為對pcl::Feature類內部感興趣的使用者或開發人員的指南。 #理論入門 在它們的原始表示中,3D對映系統的概念中所定義的點僅使用其笛卡爾座標x,y,z相對於給定原點來表示。假設座標系的原點不隨時間變化,則在t1和t2獲得的兩個點p1

Listeners with several functions in Kotlin. How to make them shine?

One question I get often is how to simplify the interaction with listeners that have several functions on Kotlin. For listeners (or any interfaces) w

How does a HashMap work in JAVA

Most JAVA developers are using Maps and especially HashMaps. A HashMap is a simple yet powerful way to store and get data. But how many developers know h

How does blockchain work in 7 steps

The blocks on a blockchain are publicly available to anyone. So, if an alteration is supposed to stay undetected on a blockchain, all the blocks need to st

How to Work Through a Regression Machine Learning Project in Weka Step

Tweet Share Share Google Plus The fastest way to get good at applied machine learning is to prac

How To Work Through a Binary Classification Project in Weka Step

Tweet Share Share Google Plus The fastest way to get good at applied machine learning is to prac

Operator overload in Kotlin: Add standard operations to any class (KAD 17)

In Kotlin, as in every language, we have predefined operators to perform certain operations. The most typical are the addition (+), subtraction (-),

Functional operations with collections in Kotlin (KAD 11)

I must admit that, for me, one of the most frustrating things when writing Java ccode is the list handling. Java 8 has some improvements in this resp

Ninja Functions in Kotlin. Understanding the power of generics (KAD 12)

The combined use of several Kotlin features mixed with the use of generics allow to create functions that will greatly simplify your code, while main

Classes in Kotlin: More power with less effort (KAD 03)

Classes in Kotlin are as simple as possible so that you can express the maximum amount of logic with the less code possible. I’ll show quickly how yo

Data Classes in Kotlin: save a good bunch of lines of code (KAD 10)

We’ve already seen the classes in an earlier article, but data classes go a little further in helping us simplify our code. What are data classes? A

Writing a RecyclerView Adapter in Kotlin (KAD 16)

An interesting way to see how Kotlin simplifies your life is by creating a RecyclerView Adapter. You’ll see that the code can be organized in such a

Variables in Kotlin, differences with Java. var vs val (KAD 02)

In this second chapter we will see how variables work in Kotlin, what is val and var , and when to use one or the other. I wanted to start from he

Say goodbye to NullPointerException. Working with nulls in Kotlin (KAD 19)

It had taken me too long to write an article to one of the most important parts of Kotlin: the treatment of nullity. Tony Hoare, the creator of the i

Extension functions in Kotlin: Extend the Android Framework (KAD 08)

Extension functions are a really cool feature that Kotlin provides, and that you’ll find yourself using a lot when writing Android Apps. We have to a

Property delegation in Kotlin: Assign values in Android without having the context (KAD 15)

As we’ve seen in previous articles, properties need a default value, they can’t be declared without assigning them a value. This is a problem, becaus

10_How swarm mode works-How nodes work

docker swarm 使用 一個或者多個 docker engine1.12 創建一個集群,叫做 swarm.一個swarm 包含一個或者多個節點:物理節點或者運行 docker engine1.12的虛擬節點總共有兩者類型的節點 : managers 和 workersManager n