Ninja Functions in Kotlin. Understanding the power of generics (KAD 12)
The combined use of several Kotlin features mixed with the use of generics allow to create functions that will greatly simplify your code, while maintaining its readability.
There are several functions included in the Kotlin library that are really useful, and once you have mastered some concepts they will be also very easy to use.
with function
Though there are several similar functions in the Kotlin standard library, I’m going to focus on with
to break it into pieces.
What does this function allow? With it, we can make blocks of code that use a variable as its context, so that we don’t need to repeat its name every time we use it.
They can replace the builders, without creating a specific one for each class.
For example, going back to the case of the ViewGroup
we had in the previous article, we could convert this code:
12 | val childViews=(0..viewGroup.childCount-1).map{viewGroup.getChildAt(it)} |
into this:
Want to learn Kotlin?
Check my free guide to create your first project in 15 minutes!
1234 | with(viewGroup){val childViews=(0..childCount-1).map{getChildAt(it)}} |
As you can see, the code inside the brackets behaves as if it were code inside the class itself.
How do we get this? We have already seen it before: with an extension function.
Extension functions as arguments for other functions
Things are getting more complicated, but this is so useful that you need to know about it.
You can define an extension function as a parameter for another function.
How would you implement the with
function to be able to execute the previous example? The simplest would be this:
1234 | inline fun with(view:ViewGroup,f:ViewGroup.()->Unit){view.f()} |
The previous code receives a ViewGroup
as a parameter, and an extension function that applies to ViewGroup
. Nothing prevents the ViewGroup
from executing that function.
But this is too constrained. Are we going to need a similar function for each type of data?
Of course not.
Generic types
We can convert the above function to a generic one quite easily. Just replace ViewGroup
with T
:
1234 | inline fun<T>with(obj:T,f:T.()->Unit){obj.f()} |
Now it can be used by any type. An example:
123456 | with(textView){text="Hello World"visibility=View.VISIBLEtextSize=sp(14).toFloat()} |
But here we are missing out on an important power we were talking about at the beginning: that of acting as a builder.
Return a value of the Generic type
If we want it to act as a real builder, we need the constructed value to be returned somehow:
12345 | inline fun<T>with(obj:T,f:T.()->Unit):T{obj.f()returnobj} |
That way, our code would look like this:
123456 | val textView=with(TextView(this)){text="Hello World"visibility=View.VISIBLEtextSize=sp(14).toFloat()} |
sp()
is a function from Anko library, which we have talked about before in this series of articles.
If you look at the official definition of the function, it is very similar to what we have done:
12 | publicinline fun<T,R>with(receiver:T,block:T.()->R):R=receiver.block() |
The main difference is that the extension function returns a value that may be different from the one being passed as an argument.
To achieve the same result using the regular with
function, we would need to do the following:
1234567 | val textView=with(TextView(this)){text="Hello World"visibility=View.VISIBLEtextSize=sp(14).toFloat()this} |
The last line implies that the object that is executing the extension function will be returned.
Other interesting functions
There is a function that works very similar to what we wanted to get in the previous section, and that is called apply
.
apply
Instead of passing the object by parameter, this function acts as an extension function for that object:
123456 | val textView=TextView(this).apply{text="Hello World"visibility=View.VISIBLEtextSize=sp(14).toFloat()} |
let
If the corresponding object is not null, it will execute the code inside the function:
12 | textView?.text?.let{toast(it)} |
The text will be displayed in a toast only if both the TextView
and the text are not null.
Conclusion
Using the power of generic types combined with extension functions, we can do very interesting things.
I encourage you to create your own functions that allow you to make your daily work easier.
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.
SharesLike this:
Loading...Related
相關推薦
Ninja Functions in Kotlin. Understanding the power of generics (KAD 12)
The combined use of several Kotlin features mixed with the use of generics allow to create functions that will greatly simplify your code, while main
Kotlin Demystified: The power of `when`
I have a confession. I’m a bit of a gamer. The Legend of Zelda games are particular favorites. Imagine my excitement when I learned there were “randomizers
Extension functions in Kotlin: Extend the Android Framework (KAD 08)
Extension functions are a really cool feature that Kotlin provides, and that you’ll find yourself using a lot when writing Android Apps. We have to a
Nobel Prize in Chemistry 2018: Harnessing the power of evolution
They harnessed the power of evolution The power of evolution is revealed through the diversity of life. The 2018 Nobel Laureates in Chemistry have taken c
The Power of Goal-Setting in Data Science
Apply OKRs to your Data Science projectAndrew Ng, the famous AI-pioneer, teaches in his Deep Learning Specialization that every Data Science project should
CF 1005C Summarize to the Power of Two 【hash/STL-map】
eric bre rom delete there set while == [] A sequence a1,a2,…,an is called good if, for each element ai, there exists an element aj (i≠j)
Summarize to the Power of Two(map+思維)
fin bsp you -i 出現次數 出現 exists rst init A sequence a1,a2,…,ana1,a2,…,an is called good if, for each element aiai,
揭開深度跟蹤的力量--Unveiling the Power of Deep Tracking (ECCV2018)
論文地址:Goutam_Bhat_Unveiling_the_Power_ECCV_2018_paper 文章亮點: 1、分析深度特徵和淺層特徵對跟蹤器效能的影響; 2、探究跟蹤器魯棒性和準確性之間的平衡; 3、提出新的深淺特徵的融合策略; 另:研究資料增強策略
collatz number,迴文數,love,map函式,漢若塔,佛祖鎮樓,read a word by random in 5s,the star of sand glass
1 collatz number def collatz(num): '''collatz number ''' if num % 2 == 0: n = num / 2 return n elif num % 2 == 1:
論文筆記 Combining the Power of Internal and External Denoising
論文筆記 Combining the Power of Internal and External Denoising IEEE論文地址: https://ieeexplore.ieee.org/document/6528298 abstract 這篇論文是我在閱讀上一篇論文,影
1005C Summarize to the Power of Two (貪心 + 煞筆的我寫了一發離散化)
Summarize to the Power of Two 題意:給定一個數組,問陣列中每一個元素 a[i] , 是否存在另一個元素 a[j], 使 a[i] + a[j] 是 2 的次冪, i != j 思路:貪心,先打出足夠的
On the power of technologic icebreakers, a UX case study on how adults and teens could write…
On the power of technologic icebreakers, a UX case study on how adults and teens could write stories together with hashtags.Designing for familiesFor my fi
Harness the Power of Augmented Reality with Camera Effects Platform
Facebook has long been a place where people connect and communicate with one another by sharing personal stories, photos, and videos about their lives. Las
5 App Ideas to Unleash the Power of Mobile Machine Learning
With over 2 billion active Android devices and over 1 billion active iOS users, the mobile market provides the most engaging and profitable market to build
The Power of Voice: Amazon Alexa (Part 1)
While undertaking new concept development within the Anthemis Foundry, I couldn’t resist tapping into the possibilities of voice interfaces across industri
Unleash the power of Slack App
1. Create NodeJS serverCreate a new NodeJS project by following these steps:Update package.json with the following content. This step is important for the
Scott Amyx Speaking on the Power of AI Data Analytics (Video)
All of you play a critical role in the regional and national economy. Small businesses and family owned businesses are the backbone of this country. In ord
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
The power of scratching your own itch
The power of scratching your own itchTo build a successful product, you also have to USE itOriginally published on JOTFORM.COMThe best business ideas usual
The power of doing nothing at all
The power of doing nothing at allOriginally published on JOTFORM.COMThe old crocodile was floating at the river’s edge when a younger crocodile swam up nex