Static extension methods in Kotlin

后端 未结 8 2383
生来不讨喜
生来不讨喜 2020-12-05 03:55

How do you define a static extension method in Kotlin? Is this even possible? I currently have an extension method as shown below.

public fun Uber.doMagic(co         


        
8条回答
  •  悲哀的现实
    2020-12-05 04:25

    I'm also quite fond of having the possibility to add static extension methods in Kotlin. As a workaround for now I'm adding the exntension method to multiple classes instead of using one static extension method in all of them.

    class Util    
    
    fun Util.isDeviceOnline(context: Context): Boolean {
        val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connMgr.activeNetworkInfo
        return networkInfo != null && networkInfo.isConnected
    }
    
    fun Activity.isDeviceOnline(context: Context) = { Util().isDeviceOnline(context) }
    fun OkHttpClient.isDeviceOnline(context: Context) = { Util().isDeviceOnline(context) }
    

提交回复
热议问题