Android app development with Kotlin (III): extended functions and default values, kotlinandroid

Source: Internet
Author: User

Android app development with Kotlin (III): extended functions and default values, kotlinandroid

This is the third article about Kotlin.


Original article title: Kotlin for Android (III): Extension functions and default values


Antonio Leiva (

Original article published:



After you understand the basic knowledge of Kotlin and how to configure your project, we can now talk about What Kotlin can do for us, but these Java cannot do. Remember, if you have any questions about the Koklin language, you can refer to the official documentation. The official documents are well organized and easy to understand. In this way, I will not cover the content of the basic language.


Extended Functions


The Kotlin Extension function allows us to add new functions to the class without changing the existing class. For example, we can add a new method for the Activity, so that we can display toast in a more simple term:


1 fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT){
2     Toast.makeText(this, message, duration).show()3 }


We can declare this function anywhere (such as in an utils file) and use it as a common method in our Activity:


1 override fun onCreate(savedInstanceState: Bundle?) { 2     super<BaseActivity>.onCreate(savedInstanceState)
3     toast("This is onCreate!!")
4 }


To declare an extension function, simply add a class name before the function name. The function is imported to the class at the call.


This helps us simplify the code and limit the closed class. However, we must be careful not to over-use them. In the end, these functions normally Replace the util class. The Util method is static and cannot be simulated (mock). Therefore, excessive use usually means that I am too lazy to create a delegate class.


This is another interesting example. I will explain another interesting concept: reified type ).


1 inline public fun <reified T : Activity> Activity.navigate(id: String) {
2     val intent = Intent(this, javaClass<T>())3 
    intent.putExtra("id", id)4 
5 }


Inline functions availableConcrete TypeThis means that we can use the internal type of the function to restore the class, instead of passing the class type with the independent variable.


Inline functionsIt is a little different from a common function. During compilation, the inline function replaces the code instead of actually calling the function. This simplifies some problems. For example, if one of the independent variables is a function, a common function creates an object within it that contains the function. Inline functions are replaced by their code where they are called, so internal objects are not required.


1 navigate<DetailActivity>("2")


With the concrete type, we can create intent inside the function; with the extension function, we can directly callStartActivity ().


Optional parameters and default values


By using the default values of the independent variables and constructor, you no longer need to overload the function. A statement can satisfy all your requirements. Let's return to the toast example:


1 fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT){
2     Toast.makeText(this, message, duration)
3 }


The second independent variable indicates the toast display duration. It is an optional parameter. If not specified, it uses Toast. LENGTH_SHORT. Now you have two methods to call this function:


1 toast("Short Toast!!")2 toast("Long Toast!!", Toast.LENGTH_LONG)


In the second example, we may want to add the independent variable for the lollipop transition:


1 inline public fun <reified T : Activity> Activity.navigate(2 
        id: String,3         sharedView: View? = null,4 
        transitionName: String? = null) {5     ...6 


Now we have two different methods to call the same function:


1 navigate<DetailActivity>("2")2 navigate<DetailActivity>("2", sharedView, TRANSITION_NAME)


There is even a third method, but it doesn't make much sense in this case, but it helps us to understand another concept: We can use the parameter name to determine which parameter we want to call:


navigate<DetailActivity>(id = "2", transitionName = TRANSITION_NAME)


Optional parameters can also be used for default constructor, so that you can obtain multiple reloads in a declaration. Custom views are a special example, because in Java, they require multiple constructors to work normally. This will be explained in the next article.




With these two concepts, we can save a lot of code and even implement things that are not possible in Java. Kotlin is highly expressive and concise. The next article describes the Kotlin Android extension, which allows us to automatically inject views into the Activity and how to generate custom views in Kotlin.


Remember to view the code of the example and see its actual application.


Previous Article:


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.