1. 程式人生 > >Kotlin for Android (III): Extension functions and default values

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

Now that you know the basics about Kotlin and how to configure your project, it´s time to talk about some interesting things that Kotlin can do for us and Java can´t. Remember that if you have some doubts about Kotlin language, you can always refer to the official reference. It´s very well organized and easy to understand, and I won´t be covering basic language stuff on this articles.

Extension functions

Kotlin extension functions will let us add new functions to existing classes that wouldn´t be able to be modified otherwise. We can, for instance, add a new method to an activity that let us show a toast in a much more simple nomenclature:

fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {

    Toast.makeText(this, message, duration)
.show()
}

We can declare this function anywhere (an utils file for instance), and use it in our activities as a regular method:

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

}

Declaring an extension function is as easy as adding the class name to the name of the function. The function will be added as an import to the class where it´s used.

It can help us simplify our code and push closed classes beyond their limits. But we must be careful and not overuse them. In the end, these functions will usually substitute util classes. Utility methods are static and can´t be mocked, so the overuse is usually an indicative that we feel too lazy to create a delegate class.

Here it is another interesting example that will let me explain another interesting concept: reified types.

inline fun <reified T : Activity> Activity.navigate(id: String) {
    val intent = Intent(this, T::class.java)
    intent.putExtra("id", id)
    startActivity(intent)
}

Inline functions can use reified types, what means that we can recover the class from a type inside the function instead of having to pass the class type as an argument.

Inline functions are a bit different from regular functions. Inline functions will be substituted with its code during compilation, instead of really calling to a function. It will simplify some situations. For instance, if we have a function as an argument, a regular function will internally create an object that contains that function. On the other hand, inline functions will substitute the code of the function in the place where its called, so it won´t require an internal object for that.

Want to learn Kotlin?

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

navigate<DetailActivity>("2")

Using a reified type, we can create the intent inside of a function, and using an extension function, we can call startActivity() directly.

Optional parameters and default values

Thanks to default values on arguments and constructors, you´ll never need to overload a function anymore. One declaration can meet all your requirements. Back to the toast example:

fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT){

    Toast.makeText(this, message, duration)
.show()
}

The second argument refers to the toast duration. It´s an optional parameter that, in case of not being specified, will use Toast.LENGTH_SHORT. Now you have two ways to call this function:

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

Regarding the second example, we could want to add some arguments for lollipop transitions:

inline fun <reified T : Activity> Activity.navigate(

        id: String,

        sharedView: View? = null,

        transitionName: String? = null) {
    
    
    ...

}

We now have two different ways to call the same function:

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

And even a third, that wouldn’t make much sense in this situation, but helps us understand another concept: we can use parameter names to decide which parameters we want to call:

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

Optional parameters can also be used in the default constructor, so you could get many overloads in a single declaration. Custom views are a special case, because they need more than one constructor to work properly in Java, but I´ll be covering this in next article.

Conclusion

With these two ideas, we can save a lot of code and even do things that are impossible in Java. Kotlin is really expressive and concise. Next article will cover Kotlin Android Extensions, which let us inject views automatically in our activities, and how to create custom views in Kotlin.

Remember taking a look to the example repository to see it in action.

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

相關推薦

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

Now that you know the basics about Kotlin and how to configure your project, it´s time to talk about some interesting things that Kotlin can do for u

Kotlin for Android (IV): Custom Views and Android Extensions

After reading what can do for you, you might be wondering what´s next. As we talked in , this language makes Android development much simpler and th

Who is Open Source? Android O Preview 3. Kotlin for Android. And Vaadin 8!

GitHub Survey: Open Source is Raining Men! A 2017 GitHub survey of 5500 randomly selected participants, most of whom work on GitHub.com open source pro

更新 是 可用的 針對 安卓 軟件開發包和工具 Updates are available for android software development packages and tools

安卓 模擬器 軟件 ide software ava -m android 設置 作者:韓夢飛沙 Author:han_meng_fei_sha 郵箱:[email protected]/* */ E-mail: 313134555 @qq.com

快速切換至Kotlin for Android模式

前言 關於Kotlin的文章,已經構思了很久。一直不知道該怎麼寫。文件式文章?那不如直接看文件,何必需要我再多“嗶嗶”呢。思來想後,決定寫一篇快速在Android開發中感受Kotlin的其妙的文章。 說實話,最開始搞Kotlin我是拒絕的。為啥?因為完全沒有感覺到用它替換Java開發有什麼實質性的改變;而

極簡Kotlin-For-Android(一)

安裝 Kotlin 外掛 Android Studio 3.+ 已經有了 Kotlin 外掛,如果是更早的版本,點選 Android Studio | File | Settings | Plugins,搜尋 Kotlin ,安裝,重啟 Android Studio . 建立工程 點選 Android

極簡Kotlin-For-Android(二)

上一篇我們做到了從網路獲取資料,並寫好了實體類.接著我們需要建立domain層,這一層為app執行任務. 構建domain層 首先需要建立command: public interface Command<T> { fun execute() : T } 複製程式碼 建立DataMap

Blog-08-《一週快速上手Kotlin For Android》-之ArrayList

在 Kotlin 中沒有實現和 Java 一樣的 List 集合,而是使用了和 Java 一樣的 ArrayList 集合。Kotlin 中提供了以下四種函式方法來使用 ArrayList,分別是 1、listOf()2、listOfNotNull()3、mutableListOf()4、arraylistO

Blog-06-《一週快速上手Kotlin For Android》-之When分支

—《一週快速上手Kotlin For Android》簡介目前Kotlin已正式成為Android的官方語言,作為Android開發者來說,學習和了解Kotlin也是屬於理所當然的事情,興許你覺得Jav

Blog-04-《一週快速上手Kotlin For Android》-之Activity詳細用法

—《一週快速上手Kotlin For Android》簡介 目前Kotlin已正式成為Android的官方語言,作為Android開發者來說,學習和了解Kotlin也是屬於理所當然的事情,興許你覺得Java對於你來說才是真正的開發”利器”,使用Java你能發揮

Kotlin for Android

在Google IO 2017 大會上,Google將 Kotlin列為 Android官方開發語言,Android Studio 3.0 也預設集成了Kotlin外掛。 如果您是更早的版本,點選Android Studio File->Settin

Blog-07-《一週快速上手Kotlin For Android》-之陣列

—《一週快速上手Kotlin For Android》簡介目前Kotlin已正式成為Android的官方語言,作為Android開發者來說,學習和了解Kotlin也是屬於理所當然的事情,興許你覺得Java對於你來說才是真正的開發”利器”,使用Java你能發揮更高的效率,當然,如果如此你還是可以繼續使用Java

Kotlin for Android(九)Kotlin集合

一、結構 集合在我們實際開發中用的還是比較頻繁的,Kotlin中的集合不同於Java中的集合, Kotlin中的集合根據“是否可變”,分為兩派:可變集合與不可變集合(可變集合可以在初始化後add新資料,不可變集合只能get資料,不能add資料),而後者是 在前

一步步學習kotlin for android(三) kotlin省略findviewById

findViewById      今天的內容涉及到findViewByID,android語言原來這個特別繁瑣,現在好了,kotlin語言,直接拿來佈局裡面的id用,省去好多重複工作量啊 在使用kotlin的id之前,需要先在builde.gradle裡引入這個 app

Kotlin for Android Developers

If at any time you have tried to investigate on your own, then you are aware of the amount of time we sometimes spend to find the solution we are loo

Kotlin for Android (II): Create a new project

After getting a light idea of, it´s time to configure Android Studio to help us develop Android apps using Kotlin. It requires some steps that only n

Kotlin for Android (I): Introduction

Kotlin is one of the many JVM based languages that are starting to emerge as a possible Java successor in Android development. Java is one of the mos

Kotlin for Android Developers: The book

Hi dear reader. Today it’s a very special post, because I’m really happy to announce the release of my first book: Kotlin for Android Developers is

12 reasons why you should start using Kotlin for Android today

Even now that Kotlin is an officially supported language to write Android Apps, you may still feel that there are not enough reasons for a change. Ja

Android Developers Blog: Kotlin Momentum for Android and Beyond

Posted by James Lau (@jmslau), Product Manager Today marks the beginning of KotlinConf 2018 - the largest in-person gathering of the Kotlin community a