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 the above snippet of code, we can convert any Integer (Int) to a RationalNumber by snippet example given below
val no : Int = 0;
val rNo: RationalNumber = no.r()
The above snippet has explicit type identification provided for the Integer and RationalNumber which is provided only for understanding as the Kotlin runtime can automatically infer these as it supports a very concise code and has static type inference.
Example
The below is a sample to build an extension to generate camel cased strings
fun String.toCamelCase(): String {
val segments = this.split(" ")
var result = ""
for (segment in segments) {
result += "${segment.toFirstCharUpper()} "
}
return result
}
fun String.toFirstCharUpper(): String {
val firstChar = this[0].toUpperCase();
return firstChar + this.substring(1, this.length)
}
This can be consumed as below,
println("hi how are you".toCamelCase())
which generates the below output
Hi How Are You
Comments
Post a Comment