I would like to use this function in multiple classes:
fun <T> T?.ifNull(function: (T?, s:String) -> Unit) {
}
How can I accomplish this?
This is how I would like to use it:
class A{
fun <T> T?.ifNull(function: (T?, s:String) -> Unit) {
}
}
class B{
constructor(){
val a = A()
//I want to use the function here
}}
Kotlin extension function example For doing this we create an extension function for MutableList<> with swap() function. The list object call the extension function (MutableList<Int>. swap(index1: Int, index2: Int):MutableList<Int>) using list. swap(0,2) function call.
In Kotlin we use a single colon character ( : ) instead of the Java extends keyword to extend a class or implement an interface. We can then create an object of type Programmer and call methods on it—either in its own class or the superclass (base class).
If the extension is defined at the top level of the class, it can access all the private variables and functions of that class. If the extension function is defined outside the class, it can not access the private variables or functions of that class.
Extension methods cannot access private variables in the type they are extending.
If you define an extension function as a member of a class A
, that extension function is only usable in the context of A
. That means, you can use it inside A
directly, of course. From another class B
though, it's not directly visible. Kotlin has so called scope functions like with
, which may be used for bringing your class into the scope of A
. The following demonstrates how the extension function is called inside B
:
class B {
init {
with(A()) {
"anything".ifNull { it, s -> }
}
}
}
As an alternative, and this is mostly the recommended approach, you would define extension functions top-level, i.e. in a file directly:
fun <T> T?.ifNull(function: (T?, s: String) -> Unit) {
}
class A {
init {
"anythingA".ifNull { it, s -> }
}
}
class B {
init {
"anythingB".ifNull { it, s -> }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With