Kotlin — Delegate Properties to Validate Value of Your Class
Please tell me, if you have a case that which you should filter value to your object class. What should you do? the common case is to validate the condition of value before storing on an object during or after instantiation. Below is an example code before inputting it into UserProfile
, check the condition, then trim the character, after that convert to uppercase for name only.
Hmm, looks like those approach is common behavior, but the problem is you need to create validation for each you want to put in UserProfile
object, and it's not effective. the other approach you can create an extensions function, but it's not our purpose for this article, so let's see if we can use delegation properties.
Yeah, now we can use this every time, no need to create validation before on object. but I think we can improve it a little bit, you can see the code write twice validation although it just only differentiates by value containing “@”. So how we can improve?
Using a class that extends ReadOnlyProperty
or ReadWriteProperty
Interface can look better. Because that Interface defines getValue()
that used to provide the current value of the delegated property for reading. The purpose same as the name, the interface ReadOnlyProperty
cant write, only Read, so setValue
is not provided. The ReadWriteProperty
(FYI ReadWriteProperty
is inherited from ReadOnlyProperty) defines setValue() methods that can be used as update value of the value property.
Based on those explanations we need to create ValidateDelegate
class, after that, we create a new variable to temp store value, then we need to pass the required value parameter to setValue() and getValue().
Above is an example of how to use ValidateDelegate
and using operator
keyword for setValue()
and getValue()
method. I only use name
variable for example to make it short, you can create email
validation as well. After you implement the code above you can use that for all classes that need validation of the variable, the reusability of ValidateDelegate
.
Property delegation has a powerful function. Tips and exploration is needed to adapt to the real use case. The purpose of delegation is to write code that can manage the properties and support the shared logic to all classes that needed to use that. So we can increase our reusability code.