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 )
delegated properties.
16.2 Delegated Properties There are some kind of common behaviours we may need in a property that would be interesting to be reused, such as lazy values or observable properties. Instead of having to declare the same code over and over again, Kotlin provides a way to delegate the code a property needs to another class. This is know as a delegated property. When we use get or set from a property, the getValue and setValue of the delegated property are called. The structure of a property delegate is: 1 class Delegate 2 fun getValue(thisRef: Any?, property: KProperty<*>): T { 3 return ... 4 } 5 6 fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { 7 ... 8 } 9 } The T is the type of the property that is delegating its behaviour. The getValue function receives a reference to the class and the metadata of the property. The setValue function also receives the value that is being assigned. If the property is immutable ( val ), it will only require the getValue function. This is how the property delegate is assigned: 16 Application Singleton and Delegated Properties 58 1 class Example { 2 var p: String by Delegate() 3 } It uses by reserved word to specify the delegation. 16.3 Standard Delegates There exists a set of standard delegates included in the Kotlin standard library. These are the most common situations where a delegate is really useful, but we could also create our own. Lazy It takes a lambda that is executed the first time getValue is called, so the initialisation of the property is delayed up to that moment. Subsequent calls will return the same value. This is very interesting for things that are not always necessary and/or require some other parts to be ready before this one is used. We can save memory and skip the initialisation until the property is required. 1 class App : Application() { 2 val database: SQLiteOpenHelper by lazy { 3 MyDatabaseHelper(applicationContext) 4 } 5 6 override fun onCreate() { 7 super.onCreate() 8 val db = database.writableDatabase 9 } 10 } In this example, the database is not really initialised until it’s called first time in onCreate . At that moment, we are sure the application context exists and is ready to be used. The lazy operation is thread safe. You can also use lazy(LazyThreadSafetyMode.NONE) { ... } if you’re not worried about multi- thread and want to get some extra performance. 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