Kotlin for Android Developers
Download 1.04 Mb. Pdf ko'rish
|
Kotlin for Android Developers Learn Kotlin the Easy Way While Developing an Android App ( PDFDrive )
initToolbar()
6 toolbarTitle = intent.getStringExtra(CITY_NAME) 7 enableHomeAsUp { onBackPressed() } 8 ... 9 } Interfaces can help us extract common code from classes that share similar behaviours. It can be used as an alternative way of composition that will keep our code better organised, and it will be easier to reuse. Think where interfaces can help you write better code. 25 Generics Generic programming consists of writing algorithms without the need of specifying the exact type the code is going to use. That way, we can create functions or types that only differ in the set of types they use, improving code reusability. These units of code are known as generics, and they exist in many languages, including Java and Kotlin. In Kotlin, generics are even more important, because the high presence of regular and extension functions will increment the amount of times that generics are of some use for us. Though we’ve been using them blindly throughout the book, generics are usually one of the trickiest parts of any language, so I’m trying to explain it in the simplest possible way so that main ideas are clear enough. 25.1 Basics For instance, we can create a class which specifies a generic type: 1 class TypedClass 2 val value: T = parameter 3 } This class now can be instantiated using any type, and the parameter will use the type in the definition. We could do: 1 val t1 = TypedClass 2 val t2 = TypedClass But Kotlin is all about simplicity and boilerplate reduction, so if the compiler can infer the type of the parameter, we don’t even need to specify it: 1 val t1 = TypedClass("Hello World!") 2 val t2 = TypedClass(25) 3 val t3 = TypedClass As the third object is receiving a null reference, the type still needs to be specified because it can’t be inferred. We can go beyond and, as in Java, reduce the types that can be used in a generic class by setting it in the definition. For instance, if we want to restrict previous class to non-nullable types, we just need to do: 120 25 Generics 121 1 class TypedClass 2 val value: T = parameter 3 } If you compile previous code, you will see that t3 now throws an error. Nullable types are not allowed anymore. But restrictions can be obviously more strict. What if we want only classes that extend Context ? Easy: 1 class TypedClass 2 val value: T = parameter 3 } 4 5 val t1 = TypedClass(activity) 6 val t2 = TypedClass(context) 7 val t3 = TypedClass(service) Now every class which extends Context can be used as the type of our class. The rest of types are not allowed. Of course, types are also allowed in functions. We can construct generic functions quite easily: 1 fun 2 ... 3 } Download 1.04 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling