Kotlin Delegation by Inception
Delegating to delegates with a functional twist
I think Kotlin delegates are underused; they are the best implementation of the “favor composition over inheritance” refrain.
In the above, the ListContainer
is a List
that can be iterated through by delegating to the backing List
within itself. Delegates
are so much more than that however; fundamentally a Delegate
allows for a property to have its read and/or write semantics implemented by an arbitrary bit of code. One of the most underutilized, and therefore the least learned from in my opinion, is the map()
Delegate
.
In the above, read/writes to the User
instance are delegated to the backing map
; changes in the fields are reflected in the map
immediately. Although a neat example, most Android apps don’t have data blobs marshaled in maps
, they have it in Bundles
. A more useful Delegate
Android wise therefore would be:
This would let you write the following expressions to let you read/write from a Bundle
without having to declare extra string constants all over the place, the key is simply the property name:
The above is nice, but not very flexible as it’s an extension on the Bundle
type itself. The more interesting usages of Bundles
in Android tend to be via proxy; Intent
extras, Activity
deep link params and Fragment
arguments all internally delegate to a Bundle
instance. What would be really nice is if we could write a Delegate
that itself delegated to something else that provides a type we already know how to delegate to; or delegation by inception as I like to call it:
With the above, we can compose Delegates
to arbitrarily read and write to any type, provided the type has a reference to another type that has a ready to use Delegate
. So for Intents
, Activities
and Fragments
we can write:
With this Bundles
become so much more convenient to work with:
With this, a full User edit flow using the new FragmentResult API may look something like this:
In the above, the edited user has their name set to “Blake”, wile keeping the existing user’s last name and age. Also in UserEditFragment
, the user data will survive process death since it is stored in the arguments bundle; all this with no bundle.getParcelable(“propertyKey”)
, or fragment.arguments.getParcelable(“userKey”)
in sight.
Why stop there though? I wrote recently on how ViewBinding
makes it really easy to express Views
as a function of their State. In situations like that, it often is very helpful if the View
could remember the last bit of state it was bound to; typically to memoize animations. Now all Android View
instances let you save arbitrary bits of data in them via their setTag
and getTag
methods with unique integer resource ids. If this is making you start thinking of a map
like Delegate
for a View
that took full advantage of this, you’re in luck:
Much like with Bundles
above, if we have any class that has a reference to a View
, we can write delegates for it that internally delegate to it:
Again, just like before with Intents
, Activities
and Fragments
; any ViewBinding
or RecyclerView.ViewHolder
instance can have any arbitrary property. This is especially useful for:
RecyclerView.ViewHolder
instances, because it means you don’t ever need to subclass it again; just addprivate
var
properties that delegate to the type you want. This is the whole foundation for declarativeRecyclerViews
covered here.ViewBinding
orView
instances needing a custom animator. In the below, aTextView
has a customObjectAnimator
tightly coupled with it without needing to subclass it.
The possibilities are quite endless. JSON deserialization is one of the most common things an app has to do and libraries often use reflection at runtime to help with it. With the right Delegate
however, you could declare fields in a class and read the value from a common JSON type without the need for reflection.
In summary, Kotlin delegates are one of the best features of the language, and seem to be woefully underused. In your codebase there’s probably some utility function that does a transform that a Delegate
is better suited for. Why not add replacing it with a custom Delegate
to your New Year’s resolutions?
All the aforementioned Delegates
are bundled (pun intended) in the following dependency, and more reading about how Kotlin Delegates
under the hood can be found here.