1. 程式人生 > >Lambdas in Kotlin, and how they simplify Android development (KAD 07)

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.

The only way we can do this in Java 6 is by declaring interfaces with a single method, and creating anonymous objects that implement those interfaces.

Lambdas

, and specially the way lambdas can be defined in Kotlin, open up an infinite world of possibilities. We will see some of these usages in the following articles.

Lambdas in Kotlin

A lambda is a way of representing a function, and we already saw an example of this when explaining the setOnClickListener

 :

12 val view=findViewById(R.id.welcomeMessage)view.setOnClickListener{v->navigateWithView(v)}

As you can see, the left side defines the input values of the function (in this case a view

), and the right side declares the operation that function will perform.

How to define a function that accepts lambdas

If we wanted to define that function in Kotlin by ourselves, we would do the following:

1 fun setOnClickListener(listener:(view:View)->Unit){}

Want to learn Kotlin?

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

This is known as a Higher-Order Function, because it is a function that receives a function by parameter, or that returns a function.

Kotlin and Java interop

The natural way of calling this function would be as follows:

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

But we’ve already seen that there is a simpler way to do this, and that will also help us do very cool things that we will see right after.

This is because if the last parameter of a function is a function, we can extract it from the parentheses:

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

But in addition, if there is only one function as a parameter, we can just get rid of the parentheses:

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

DSLs creation

This allows us to create our own DSLs, which can define mini-languages. In Kotlin reference website there is an example with HTML, but here we are going to define an easier one.

Imagine that you want to create blocks of code that run on another thread. You could have a function that receives the function we want to run in the background:

123 fun doAsync(f:()->Unit){Thread({f()}).start()}

This function creates a thread that executes a Runnable which runs the function received as an argument. As  Runnable  is a class with a single method in Java, it can be substituted by a lambda in Kotlin.

Now we can create asynchronous blocks in our code:

12345 doAsync{op1()op2()op3()}

Everything inside the braces will be executed in a secondary thread.

Inline functions

The ugly part of receiving functions as an argument is that the compiler needs to create classes for them, which can impact in the performance. But this can be easily solved by using the reserved word inline.

An inline function will have less impact in performance, because it will substitute the call to the function by its code in compilation time. So it won’t require the use of an extra object for this.

We can convert doAsync into an inline function:

123 inline fun doAsync(crossinlinef:()->Unit){Thread({f()}).start()}

The crossinline in this case is required because we are calling f() from another execution context (another lambda). Don’t worry about this too much, as the compiler will warn you when you need to use it.

Conclusion

As you can see, with lambdas we can simplify our code a lot, and even achieve things that were impossible in Java.

In addition, Kotlin’s specific nomenclature makes it possible for us to create our own “language”, and create meaningful blocks of code that do what we need.

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...

相關推薦

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

Everything to know about digital celebrities and how they could change the world

Part II: How do digital celebrities progress?MonetizationWhile a large portion of these celebrities are still in the experimental phase, there is a subset

Top 3 Reasons Why Chatbots Fail in Finance [And How to Fix Them]

We use cookies to give you the best online experience. By using our website you agree to our use of cookies in accordance with our cookie

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 (-),

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

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

<轉>How to Encourage Your Child's Interest in Science and Tech

sim challenge table nic options https fun developed advice How to Encourage Your Child‘s Interest in Science and Tech This week’s Ask-A-D

How to read version (and other) information from Android and iOS apps using Java

How to read version (and other) information from Android and iOS apps using Java https://medium.com/@mart.schneider/how-to-read-version-and-oth

How i Industrie Router Hutschiene nternationals have founded startups in Germany - and their advice

www.inhandnetworks.de Thinking of starting your own business in Germany? We have reached out to a few expat founders across the country to see how

Why (and how) to use eslint in your project

Why (and how) to use eslint in your projectThis story was written by Sam Roberts, a Senior Software Engineer at IBM Canada. It was first published in IBM d

Components testing in React: what and how to test with Jest and Enzyme.

Testing React components may be challenging for beginners as well as experienced developers who have already worked with tests. It may be interesting to co

Predictive Analytics in 2018: What's Possible, Who's Doing It, and How

In 2009, Netflix offered $1 million to anyone who could improve the quality of its recommendation engine by 10%. It took two years, but a team finally won.

What is a Security Token? A Comprehensive Guide to How They Work and Their Impact

There’s been a lot of talk about security tokens recently. But what is a security token in the first place? How do they work? And how might they impact you

Researchers develop 3D printed objects that can track and store how they are used

But these plastic parts don't have electronics, which means they can't monitor how patients are using them. Now engineers at the University of Washington

Neuroscience and Artificial Intelligence; How They are Perpetuating Each Other’s Progress

Neuroscience and Artificial Intelligence; How They are Perpetuating Each Other’s ProgressBefore I even delve into these, if not the most, existential topic

How to Sort a HashMap by Values in Ascending and Descending Order in Java 8

In the last article, I have shown you how to sort a Map in Java 8 by keys and today, I'll teach you how to sort a Map by values using Java 8 features e.g.

How to distribute your own Android library through jCenter and Maven Central from Android Studio

In Android Studio, if you wish to include any library to your application. You could just simply add a following line of dependency in mo

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

Routing in React Native apps and how to configure your project with React

Tab Navigator implements a type of navigation that exists in native iOS for many years already. Recently, Android added it to its Material design patterns

Computer Interfaces and how will they change the world?

The sensors of brain computer interfaces are the most critical part of the entire system. A sensor is some sort of device (wire, detector, camera) that pic