Static extension methods in Kotlin

后端 未结 8 2342
生来不讨喜
生来不讨喜 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:24

    Recomend you to look at this link. As you can see there, you just should declare method at the top-level of the package (file):

    package strings
    public fun joinToString(...): String { ... }
    

    This is equal to

    package strings;
    
    public class JoinKt {
        public static String joinToString(...) { ... }
    }
    

    With constans everything are the same. This declaration

    val UNIX_LINE_SEPARATOR = "\n"
    

    is equal to

    public static final String UNIX_LINE_SEPARATOR = "\n";
    
    0 讨论(0)
  • 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) }
    
    0 讨论(0)
提交回复
热议问题