1
votes

I wanted to create an extension function for Android built in ConnectivityManager class so that it can be used statically by any class in my project. I am using Kotlin only.

fun ConnectivityManager.checkInternet(context: Context): Boolean {
        val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val connection = manager.activeNetworkInfo
        if (connection != null && connection.isConnectedOrConnecting) {
            return true
        }
        return false
    }

I can access this function by creating the object of ConnectivityManager but what i want to do is to use it statically. Any possibility?

3
Does you function use ConnectivityManager in its logic? If not, what do you need it to be an extension function for? - voddan
This should be an extension on Context, not ConnectivityManager. - Marko Topolnik
It can go both ways, we can have context or an object of connectivitymanager extracted from context as argument to this function, what I exactly want to know is that can we use extension function approach on kotlin to kotlin classes for Android built in classes in static way. - Atif Rehman
Possible duplicate of Static extension methods in Kotlin - kyay10

3 Answers

5
votes

This is only possible if your class has a companion object defined:

class MyClass {
    companion object { } 
}

fun MyClass.Companion.foo() {
}

Just like regular members of the companion object, they can be called using only the class name as the qualifier:

MyClass.foo()

Unfortunately, Java classes do not have such companion objects, which is why you can’t achieve what you want.

3
votes

Quite likely this kind of extension function in not what you are looking for. I can see two approaches how you can handle it.

Either create top-level function is separate file (e.g. network.kt).

fun checkInternet(context: Context): Boolean{
    // perform check here
}

Or create extension method on Context

fun Context.checkInternet(): Boolean {
    val manager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    // I've "kotlinized" a bit your `if` statement
    return manager.activeNetworkInfo?.isConnectedOrConnecting ?: false
}

Personally, I'd prefer the approach with extension on Context.

0
votes

Your function checkInternet is defined as an extension function for your class ConnectivityManager.

If you want to use your function checkInternet like an extension method for any class, you can do this:

fun Any.checkInternet(context: Context): Boolean { val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val connection = manager.activeNetworkInfo if (connection != null && connection.isConnectedOrConnecting) { return true } return false }

and import the checkInternet function where you are using it.

Otherwise, you can make checkInternet as a static member in ConnectivityManager and use it like a static function.