Developing Android Apps using Kotlin (III): extension functions and default values
@author ASCE1885 's Github book Weibo CSDN
Original link
With the first two articles, we learned the basics of Kotlin and know how to configure the project, and this article will go on to introduce the interesting features that Java does not have and Kotlin implements. Remember that when you have any questions about Kotlin language, please refer to the official guide. This guide is well organized and easy to understand, and this article will not cover the basics of language.
Extension functions
Kotlin's extended function allows us to add new functions to existing classes without modifying the original class. For example, we can add a new function for an activity to display a toast:
fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT){? Toast.makeText(this, message, duration)?.show()}
We can declare this function anywhere (for example, in a utils file) and use it in this activity like a normal function:
onCreate(savedInstanceState: Bundle?) { super<BaseActivity>.onCreate(savedInstanceState)? toast("This is onCreate!!")?}
Declaring an extension function is simple, just add the specified class name before the function name. When called, the function is added to this class as an import.
Extension functions help us simplify the code and make great use of closed classes. But we have to be careful and not overuse it. One result of using an extension function is that it is commonly used as an alternative to tool classes. Tool functions are static and cannot be mocked, so overuse of tool functions is often the result of our lazy creation of managed classes.
Here's another interesting example to explain another interesting concept: materialized (reified) types.
public fun <reified T : Activity> Activity.navigate(id: String) {? val intent = Intent(this, javaClass<T>())? intent.putExtra("id", id)? startActivity(intent)?}
Inline functions can use the materialized (reified) type, which means that we can recover a class from a type within a function, rather than passing in the type of the class as a parameter.
There is a little difference between an inline function and a normal function. Instead of actually making function calls, the inline function makes code substitutions during compilation. In some cases, the problem can be simplified. For example, if we have a function that takes action, the normal function creates an object that contains the function internally, and the inline function will replace the function call with code directly where the function is called, so there is no need to create an inner object.
navigate<DetailActivity>("2")
Using the reified type, we can create a intent inside a function and use an extension function so that we can call StartActivity () directly.
Optional parameters and default values
With the default values for parameters and constructors, you will no longer need to perform function overloading. A function declaration can satisfy all of your needs. Let's go back to the toast example:
fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT){? Toast.makeText(this, message, duration)?}
The second parameter indicates the duration of the toast's display, which is an optional parameter, but is not explicitly specified when the default toast.length_short is used. So you have two ways of calling this function:
toast("Short Toast!!")toast("Long Toast!!", Toast.LENGTH_LONG)
Back to the second example above, we might want to add several parameters to support lollipop animations:
T : Activity> Activity.navigate(? id: String,? sharedView: View? = null,? transitionName: String? = null) {?? ...
Now we have two ways of calling the same function:
navigate<DetailActivity>("2")navigate<DetailActivity>("2", sharedView, TRANSITION_NAME)
There's even a third way, in which case it doesn't make much sense, but it helps us understand another concept: we can use parameter names to determine which parameters are called:
navigate<DetailActivity>(id"2", transitionName = TRANSITION_NAME)
Optional parameters can also be used in the default constructor, so you can declare only one constructor, but you get a lot of overloads. Custom views are a special example, and in Java they require more than one constructor to run correctly, which I'll cover in the next article.
Summarize
With extension functions and optional parameters and default values, we can save a lot of code and even do what we can't do in Java. Kotlin is really more expressive and concise. The next article will introduce Kotlin's Android extension, which allows us to automatically inject views into activities, as well as to create custom views using Kotlin.
Please remember to check the actual running of our demo example, practice the truth.
Appreciation of photography at the end of Wen
Developing Android Apps using Kotlin (III): extension functions and default values