How to add annotations to captured variables or delegated objects in Kotlin?
Create a named class:
fun myFunc(someObj: SomeObj, update: Boolean): SomeObj {
class SomeObjSubclass(someObj: SomeObj, @Transient val update: Boolean):
SomeObj(someObj.prop1, someObj.prop2, /* and so on*/), SomeInterface {
override fun doUpdate() = update
}
return SomeObjSubclass(someObj, update)
}
Notice that myFunc
is now merely a wrapper for SomeObj
. Depending on your design, you could just make myFunc
the SomeObj
subclass instead:
class MyFunc(someObj: SomeObj, @Transient val update: Boolean):
SomeObj(someObj.prop1, someObj.prop2, /* and so on*/), SomeInterface {
override fun doUpdate() = update
}
Callers would call MyFunc(...)
as if it were a function, and they would receive something assignable to SomeObj
, just like before.
You can also add a secondary constructor to SomeObj
that takes a SomeObj
, and copy the properties there
constructor(someObj: SomeObj): this(
someObj.prop1, someObj.prop2, /* and so on */
)
Then the declaration of MyFunc
can just be:
class MyFunc(someObj: SomeObj, @Transient val update: Boolean):
SomeObj(someObj), SomeInterface {
override fun doUpdate() = update
}