Introduction
The operator overloading feature let's us to build custom operators. In The below example, we provide a compareTo which can help us in evaluation of the <, >, = functions in the custom object of type MyDate
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
operator override fun compareTo(other: MyDate)=when{
year != other.year -> year - other.year
month != other.month -> month - other.month
else -> dayOfMonth - other.dayOfMonth
}
}
In the above snippet, we are implementing the Comparable<T> for our MyDate type so that we can compare two instances of type MyDate as given below
println(date1 < date2)
Capabilities
This helps us in implementing custom operators to ease the use of business objects throughout the code rather than repeating code or using lots of Helpers in the code base.
Comments
Post a Comment