Mikael Quick
Mikael Quick

Reputation: 289

Kotlin call member Extension function from other class

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
}}

Upvotes: 14

Views: 6381

Answers (1)

s1m0nw1
s1m0nw1

Reputation: 82077

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 -> }
    }
}

Upvotes: 45

Related Questions