Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin call member Extension function from other class

Tags:

android

kotlin

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
}}
like image 334
Mikael Quick Avatar asked Mar 30 '18 15:03

Mikael Quick


People also ask

How do I call Kotlin extension function?

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.

How do I extend one class to another in Kotlin?

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).

Can extension methods access private members Kotlin?

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.

Can extension functions access private members?

Extension methods cannot access private variables in the type they are extending.


1 Answers

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 -> }
    }
}
like image 139
s1m0nw1 Avatar answered Sep 29 '22 11:09

s1m0nw1