1. 程式人生 > >Reified Types in Kotlin: how to use the type within a function (KAD 14)

Reified Types in Kotlin: how to use the type within a function (KAD 14)

One of the limitations that most frustrates Java developers when using generics is not being able to use the type directly.

Normally this is solved by passing the class as a function parameter, making the code more complex and unattractive.

In Kotlin, thanks to the inline functions, which we’ve already discussed

, we can use reified types that will allow us to use them within the functions.

What is this for? You’ll see, you’re gonna like it.

Reified types

As I commented earlier, by marking a type as reified, we’ll have the ability to use that type within the function.

It is important that the function that uses it is inline

, since the code needs to be replaced in the place from which it is run in order to have access to the type. The fact that types can not be used in functions is a limitation of the Java Virtual Machine, and that’s the “trick” to skip that limitation.

Navigating to an Activity

This is the most typical case applied to Android.

In Java, when we call startActivity, we need to specify the destination class as a parameter.

Want to learn Kotlin?

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

In Kotlin, we can simplify it by adding the type to the function:

123 inline fun<reifiedT:Activity>Activity.startActivity(){startActivity(Intent(this,T::class.java))}

Navigating to an Activity is now as easy as this:

1 startActivity<DetailActivity>()

FindView with casting

Something that not many Android developers use in Java and that is quite helpful is using generics to return the objects casted to the type of the variable that the result is assigned to.

In Java, you can create a function like this:

123 public<TextendsView>TfindView(Activity activity,intid){return(T)activity.findViewById(id);}

And then use it to return the casted object:

12 TextView textView=Utils.findView(activity,R.id.welcomeMessage);

Something similar can be done with Kotlin, but easier thanks to extension functions:

123 fun<T:View>Activity.findView(id:Int)=findViewById(id)asTval textView=activity.findView<TextView>(R.id.welcomeMessage)

But in both cases you’ll find that the compiler can’t be sure that the cast is valid, because it doesn’t have access to the type of T, so it will show a warning.

With reified types, you can avoid this issue:

12 inline fun<reifiedT:View>Activity.findView(id:Int)=findViewById(id)asT

Conclusion

With reified types you can do things that are impossible in Java, and even do some other functions safer.

Now, you can avoid passing an argument of type Class to your functions.

Besides, thanks to extension functions, you can create new functions over frameworks such as Android, which already use this in some parts of its API (as the startActivity method does).

And if you want to start using Kotlin to develop your own apps, I recommend you to take a look a the free guide and Kotlin for Android Developers book.

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

相關推薦

Reified Types in Kotlin: how to use the type within a function (KAD 14)

One of the limitations that most frustrates Java developers when using generics is not being able to use the type directly. Normally this is solved b

how to use “request” object within a function in jsp

request is accessible inside the scriptlet expressions, because it’s an argument of the method in which these expressions are evaluated (_jspService). But

how to use the volatile keyword keil51 ?

       1. 例如對外部暫存器的讀寫。         對有些外部裝置的暫存器來說,讀寫操作可能都會引發一定硬體操作,但是如果不加volatile,編譯器會把這

How to Use the Facebook Budget Optimization Tool for Improved Results : Social Media Examiner

Wondering how to allocate your budget to reach the most effective Facebook audiences? Facebook's Budget Optimization tool uses an algorithm to automaticall

How To Use The React Context API

How To Use The React Context APIReacting to ContextIf you’ve recently been hearing a lot about the new React Context APIand wanted to know more about it, t

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

How to Use the Keras Functional API for Deep Learning

Tweet Share Share Google Plus The Keras Python library makes creating deep learning models fast

How to Use the Cognitive Service from Microsoft (LUIS) with Bot Builder

How to Use the Cognitive Service from Microsoft (LUIS) with Bot Builderby SERHIY SKOROMETS, Software Developer at ElifTechConversational chatbots were crea

[iOS] How to round the corners of a button

如何做出圓角的按鈕?比我想像中的簡單,其實一行指令(buyButton.layer.cornerRadius)就完成了。 實作出來的效果,我是用 cornerRadius = 5 You can manipulate the CALayer of your button to do this pre

How to use AI in the insurance value chain: customer service and policy administration

How do you approach customer service and policy administration within your organization? In this blog post, I'll demonstrate how artificial intelligence (A

How to use APIs with Pandas and store the results in Redshift

How to use APIs with Pandas and store the results in RedshiftHere is an easy tutorial to help understand how you can use Pandas to get data from a RESTFUL

How to use "man" effectively in the development of Linux

man is the system's manual pager.      The table below shows the section numbers of the manual followed by the types of pages they cont

How To View the HTML Source in Google Chrome

inner eve spi together member mes mnt line split Whether you are new to the web industry or a seasoned veteran, viewing the HTML source o

How to Get the Length of File in C

code class clas body position pre -c set == How to get length of file in C //=== int fileLen(FILE *fp) { int nRet = -1; int nPosB

[Tensorflow] 統計模型的引數數量 How to calculate the amount of parameters in my model?

import logging logging.basicConfig(level=logging.INFO, format='%(message)s', filemode='w', filename=config.logger) def _params_usage(): total

How to Install The Latest Eclipse in Ubuntu 16.04, 15.10?

How to Install The Latest Eclipse in Ubuntu 16.04, 15.10? 1. Install Java Don’t have Java installed? Search for and install OpenJDK Java 7 or

How to Use 3 Kinds of NetSuite Billing Types

Project management in NetSuite offers a great deal of flexibility when managing projects and resources. With that flexibility comes the options t

[轉]How to display the data read in DataReceived event handler of serialport

本文轉自:https://stackoverflow.com/questions/11590945/how-to-display-the-data-read-in-datareceived-event-handler-of-serialport   問: I have the followin

How to list the open file descriptors (and the files they refer to) in my current bash session

轉載 自https://unix.stackexchange.com/questions/333186/how-to-list-the-open-file-descriptors-and-the-files-they-refer-to-in-my-curren Yes, this will li