Kotlin miniguide #7 Extension functions

Similarly to C# extension methods, it’s possible to extend a class without modifying the class code by using the extension functions.


fun Int.isGreaterThan(number : Int) : Boolean {

    return this > number

}

//now we have added a new "functionality" to the Int

//class

val a =2

val b = 3

val c a.isGreaterThan(3)

Extension functions are resolved statically not at run time.

Un pensiero riguardo “Kotlin miniguide #7 Extension functions

  1. Extension method for fragment instantiation:
    “`
    inline fun instanceOf(vararg params: Pair) : T
    = T::class.java.newInstance().apply { arguments = bundleOf(*params) }
    “`

    "Mi piace"

Lascia un commento