Skip to main content

Posts

Showing posts with the label extensions

Extension Functions in Kotlin

Introduction Extension functions help us a lot when implementing re-usable code. In many cases where we are required to provide re-usable code, but unable to add the function to the class may be because it was from a 3rd party library or from an external module, we end up adding a pile of helpers in getting the job done. In Java, this feature is not supported unlike in C# and other languages. The drawback of this is we have to create a helper class and create static methods which are not tied to the types. This results in helper classes being used and is not more readable than having the method as an extension or part of the type. data class RationalNumber( val numerator: Int , val denominator: Int ) fun Int.r(): RationalNumber = RationalNumber( this , 1 ) fun Pair< Int , Int >.r(): RationalNumber = RationalNumber( this .first, this .second) The above snippet explains the use of extension functions  which help us in extending the Integer and the Pair Types. After building t