Questions tagged [kotlin-delegate]

The Delegation pattern has proven to be a good alternative to implementation inheritance, and Kotlin supports it natively requiring zero boilerplate code.

Kotlin-Delegation

Class Delegation

The Delegation pattern has proven to be a good alternative to implementation inheritance, and Kotlin supports it natively requiring zero boilerplate code. A class Derived can inherit from an interface Base and delegate all of its public methods to a specified object:

interface Base {
    fun print()
}

class BaseImpl(val x: Int) : Base {
    override fun print() { print(x) }
}

class Derived(b: Base) : Base by b

fun main(args: Array<String>) {
    val b = BaseImpl(10)
    Derived(b).print() // prints 10
}

The by-clause in the supertype list for Derived indicates that b will be stored internally in objects of Derived and the compiler will generate all the methods of Base that forward to b.

Note that overrides work as you might expect: The compiler will use your override implementations instead of those in the delegate object. If we were to add override fun print() { print("abc") } to Derived, the program would print "abc" instead of "10".

Delegated Properties

There are certain common kinds of properties, that, though we can implement them manually every time we need them, would be very nice to implement once and for all, and put into a library. Examples include:

  • lazy properties: the value gets computed only upon first access;
  • observable properties: listeners get notified about changes to this property;
  • storing properties in a map, instead of a separate field for each property.
28 questions
2
votes
0 answers

Kotlin Delegate with MultiDex on Android below 21

I have the following Delegate... fun integerPref(initialValue: Int) = object : ObservableProperty(initialValue) { override fun afterChange(property: KProperty<*>, oldValue: Int, newValue: Int) { getSharedPreference(INTEGER_PREF,…
1
vote
0 answers

How does koltin delegate access class delegated method?

There are some interfaces or classes blow: interface ITagProvider { fun getTag(): String } interface ITagPrinter { fun printTag() } class TagPrinter(val tagProvider: ITagProvider): ITagPrinter { override fun printTag() { …
leimenghao
  • 226
  • 1
  • 10
1
vote
1 answer

Implementing observable properties that can also serialize in Kotlin

I'm trying to build a class where certain values are Observable but also Serializable. This obviously works and the serialization works, but it's very boilerplate-heavy having to add a setter for every single field and manually having to call…
1
vote
2 answers

Kotlin delegate's ReadOnlyProperty with generic type value dose not cast correctly in getValue

I am expecting to see the output black white with below code package delegate import kotlinx.coroutines.runBlocking import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty open class Color(private val name: String) { …
Arst
  • 3,098
  • 1
  • 35
  • 42
1
vote
1 answer

Kotlin is it possible to delegate function or function parameters?

I want to have for example: class Foo { fun doSomething(arg1: String, arg2: String, arg3: Boolean) } class FooDelegate { //different fun name fun execute by Foo::doSomething } Either with reflection or other way. What I currently have…
htafoya
  • 18,261
  • 11
  • 80
  • 104
1
vote
1 answer

NullPointerException (NPE) when using Kotlin property delegate with by

I have a class that takes user inputs in a text field and converts them to an any class using the supplied functions class GenericTextFieldDelegate( private val initBlock: () -> TextView, private val getConversion: (String?) -> T?, …
Mark Gilchrist
  • 1,972
  • 3
  • 24
  • 44
1
vote
1 answer

How to nest multiple property delegates in Kotlin

I've come accross a case where I want to "chain" mutliple delegates (piping the output of one into the other). This seems to be possible: private val errorLogList by listSO(listOf>(), SODest.NONE, publicSOAccessRights()) val…
p_0g_amm3_
  • 451
  • 6
  • 14
1
vote
1 answer

Dagger Construction Injection with Kotlin Class Delegation

I have the following Kotlin Class: @ExperimentalCoroutinesApi class SharedPrefClient @Inject constructor(private val prefs: SharedPreferences) : SharedPreferences by prefs { ... } In Dagger, I get the following error while building…
zoha131
  • 1,758
  • 2
  • 16
  • 18
1
vote
1 answer

Is it possible to provide multiple delegate types with a single class?

I'd like to provide multiple different delegates from a single class, with differing types. For example: class A { val instanceOfB = B() val aNumber: SomeType by instanceOfB val anotherNumber: SomeOtherType by instanceOfB } class B { …
howettl
  • 12,419
  • 13
  • 56
  • 91
0
votes
1 answer

How to observe a reference variable?

I have a class below that updates a data variable. How can I observe when this variable changes? object Manager { private var data: Type = B() fun doWork{ while(active) { if(conditionA) data = A() …
J_Strauton
  • 2,270
  • 3
  • 28
  • 70
0
votes
1 answer

How can a Delagetes.observable in a BroadcastReceiver be unit tested?

How can i test a Delegates.Observable that is inside a BroadcastReceiver. I need to get battery level of device and check if it's just went below or above pre-defined critical level, and upload to server using UseCase of clean architecture. I used…
Thracian
  • 43,021
  • 16
  • 133
  • 222
0
votes
3 answers

Android studio is not able to resolve import

I am trying to work on a sample project to learn MvRx. However, seems something is wrong. Android Studio is not able to find and import activityViewModel automatically. 1) I tried to import it manually by writing its package name but it is still…
Hesam
  • 52,260
  • 74
  • 224
  • 365
-1
votes
1 answer

Nested property delegation in Kotlin

As mentioned in the official tutorial, we can store properties in a Map and delegate a class to it: class User(val map: Map) { val name: String by map val age: Int by map } However, sometimes we store non-trivial…
1
2