Kotlin for Android Developers
Start an activity: reified functions
Download 1.04 Mb. Pdf ko'rish
|
Kotlin for Android Developers Learn Kotlin the Easy Way While Developing an Android App ( PDFDrive )
23.3 Start an activity: reified functions
The final step consists of starting the detail activity from the main activity. We can rewrite the adapter instantiation this way: 1 val adapter = ForecastListAdapter(result) { 2 val intent = Intent(MainActivity@this, javaClass 3 intent.putExtra(DetailActivity.ID, it.id) 4 intent.putExtra(DetailActivity.CITY_NAME, result.city) 5 startActivity(intent) 6 } But this is too verbose. As usual, Anko provides a much simpler way to start an activity by using a reified function: 1 val adapter = ForecastListAdapter(result) { 2 startActivity 3 DetailActivity.CITY_NAME to result.city) 4 } What’s the magic behind reified functions? As you may know, when we create a generic method in Java, there is no way to get the class from the generic type. A popular workaround is to pass the class as a parameter. In Kotlin, an inline function can be reified, which means we can get and use the class of the generic type inside the function. In this case, we can create the intent inside the function, by calling T::class.javaClass . A simpler version of what Anko really does would be the next (I’m only using String extras in this example): 23 Creating a Detail Activity 111 1 public inline fun 2 vararg params: Pair 3 4 val intent = Intent(this, T::class.javaClass) 5 params.forEach { intent.putExtra(it.first, it.second) } 6 startActivity(intent) 7 } The real implementation is a bit more complex because it uses a long and boring when expression to add the extras depending on the type, but it doesn’t add much useful knowledge to the concept. Reified functions are, once more, a syntactic sugar that simplifies the code and improves its comprehension. In this case, it creates an intent by getting the javaClass from the generic type, iterates over params and adds them to the intent, and starts the activity using the intent. The reified type is limited to be an Activity descendant. The rest of little details are covered in the repository. We now have a very simple (but complete) master-detail App implemented in Kotlin without using a single line of Java. |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling