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
14
votes
2 answers

How to set up a listener for a variable in Kotlin

How to I set up an interface listener for detecting a variable change in Kotlin. I successful implemented the following in Java, but am running into issues doing it in Kotlin: Interface: public interface InterfaceRefreshList { public void…
Samuel
  • 395
  • 2
  • 5
  • 20
6
votes
6 answers

Calling (base) delegated function when using class delegation from within override

When overriding an interface method implemented by class delegation, is it possible to call the class which is normally delegated to from within an overriding function? Similar to how you would call super when using inheritance. From the…
Steven Jeuris
  • 18,274
  • 9
  • 70
  • 161
5
votes
2 answers

Kotlin: referring to delegate that is not passed by constructor

I want to use Kotlin delegation in a particular context. The delegate should not be passed in the constructor. I want to keep a reference to the delegate for later use in the code. From within the method that I override, say printMessage(), I still…
Ahmad Shahwan
  • 1,662
  • 18
  • 29
5
votes
2 answers

Kotlin delegate property causes a preview rendering error in Android Studio

I have created a custom property dedicated to holding properties of the view that require invalidate() call for one of my projects: class InvalidatingProperty(private var _value: T) { operator fun getValue(thisRef: View, property:…
xsw2_2wsx
  • 162
  • 2
  • 11
5
votes
1 answer

How to combine kotlin delegated property: observable, vetoable, and "by map"?

I'm trying to combine delegates/observable with vetoable (which isn't a problem after looking at the source kotlin.properties.Delegates.kt), but things got hairy when trying to also store the properties in a map. Or in other words, how to combine…
Benjamin H
  • 5,164
  • 6
  • 34
  • 42
3
votes
2 answers

Kotlin Problem Delegating to Map with DefaultValue - Language Bug?

In the following code, where MyMap trivially implements Map by delegation to impl: foo@host:/tmp$ cat Foo.kt class MyMap (val impl : Map ) : Map by impl { fun myGetValue (k: K) = impl.getValue(k) } fun main() { val my_map =…
user2297550
  • 3,142
  • 3
  • 28
  • 39
3
votes
2 answers

Why do delegate class methods getValue and setValue need to marked with operator keyword?

Here's an example from Delegated properties documentation. import kotlin.reflect.KProperty class Delegate { operator fun getValue(thisRef: Any?, property: KProperty<*>): String { return "$thisRef, thank you for delegating…
Alexander Suraphel
  • 10,103
  • 10
  • 55
  • 90
3
votes
1 answer

Android Obtain ViewModelScope so it can be used in interface delegation

My viewModel implements an interface by delegation like this: class ProductViewModel(item: Product) : ViewModel(), ItemInterface by ItemDelegator(item) Now, inside ItemDelegator I need a CoroutineScope bound to the ViewModel I simply cannot do…
Favolas
  • 6,963
  • 29
  • 75
  • 127
3
votes
0 answers

Unsupported Delegation without primary constructor

I ran into an issue with kotlin delegation where I want to delegate the interface implementation to a variable. The problem is that the superclass has some other constructors that I would not want to lose really interface Delegate class…
Breimer
  • 506
  • 8
  • 14
3
votes
0 answers

Android Data Binding does not work with Kotlin's class delegation

My ViewModel: class MyVM( app: Application, private val observableImpl: BaseObservable, /* other colaborators*/ ) : AndroidViewModel(app), Observable by observableImpl { var currencyCode: String by…
Sevastyan Savanyuk
  • 5,797
  • 4
  • 22
  • 34
2
votes
0 answers

Kotlin delegated property deserialization with Jackson

I am trying to deserialize a data class the built from a delegated property. Here is a quick snippet to reproduce my case : @JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION, defaultImpl = BaseResponseDto::class) interface ResponseDto { val name:…
2
votes
1 answer

Deserializing object to data class that contains delegated properties (inheritance with delegation)

Your question I have checked issues and docs and could not find solution. The follwing code properly serialize object (Component) to string, but deserialization from string back to insgtances of Component doesn't work. Any suggestions how to do it,…
qwetty
  • 1,238
  • 2
  • 10
  • 24
2
votes
1 answer

In Kotlin, Why Abstract class cannot be delegated using "by" keyword just like interface

interface IA { fun callMe() } abstract class AbstractA { abstract fun callMe() } // Allowed class ImplementationA(a: IA): IA by a //Why this is Not Allowed ? class ImplementationA(a: AbstractA): AbstractA() by a I could not find any…
Pankaj
  • 1,242
  • 1
  • 9
  • 21
2
votes
1 answer

(de)serializing kotlin delegate properties with jackson

How can I (de)serialize kotlin delegate properties with jackson. I have a class like this class MyClass { var a: Int = 42 set(value) { val changed = field != value field = value if (changed)…
binarynoise
  • 364
  • 3
  • 14
2
votes
1 answer

How to implement a lazy property in Kotlin that requires another property?

I need a rectangle that needs to be initialized on call. Here is my code; class EpheButton private constructor( private val text: String, private val x: Float, private val y: Float, private val projectionMatrix: Matrix4) : Disposable…
Efe Budak
  • 659
  • 5
  • 27
1
2