Kotlin for Android Developers
Download 1.04 Mb. Pdf ko'rish
|
Kotlin for Android Developers Learn Kotlin the Easy Way While Developing an Android App ( PDFDrive )
- Bu sahifa navigatsiya:
- 13.1 Simplifying setOnClickListener()
13 Lambdas
A lambda expression is a simple way to define an anonymous function. Lambdas are very useful because they prevent us from having to write the specification of the function in an abstract class or interface, and then the implementation of the class. In Kotlin, we can use a function as a parameter to another function. 13.1 Simplifying setOnClickListener() I will explain how this works using a typical example in Android: the View.setOnClickListener() method. If we want to implement a click listener behaviour in Java, we first need to write the OnClickListener interface: 1 public interface OnClickListener { 2 void onClick(View v); 3 } And then we write an anonymous class that implements this interface: 1 view.setOnClickListener(new OnClickListener() { 2 @Override 3 public void onClick(View v) { 4 Toast.makeText(v.getContext(), "Click", Toast.LENGTH_SHORT).show(); 5 } 6 }); This would be the transformation of the code into Kotlin (using Anko toast function): 1 view.setOnClickListener(object : OnClickListener { 2 override fun onClick(v: View) { 3 toast("Click") 4 } 5 }) Luckily, Kotlin allows some optimisations over Java libraries, and any function that receives an interface with a single function can be substituted by the function. It will work as if we had defined setOnclickListener() like this: 46 13 Lambdas 47 1 fun setOnClickListener(listener: (View) -> Unit) A lambda expression is defined by the parameters of the function to the left of the arrow (surrounded by parentheses), and the return value to the right. In this case, we get a View and return Unit (nothing). So with this in mind, we can simplify the previous code a little: 1 view.setOnClickListener({ view -> toast("Click")}) Nice difference! While defining a function, we must use brackets and specify the parameter values to the left of the arrow and the code the function will execute to the right. We can even get rid of the left part if the parameters are not being used: 1 view.setOnClickListener({ toast("Click") }) If the function is the last one in the parameters of the function, we can move it out of the parentheses: 1 view.setOnClickListener() { toast("Click") } And, finally, if the function is the only parameter, we can get rid of the parentheses: 1 view.setOnClickListener { toast("Click") } More than five times smaller than the original code in Java, and much easier to understand what is doing. Really impressive. Download 1.04 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling