我可以在Kotlin中使这个赋值表达式更紧凑吗?

时间:2018-04-26 15:06:12

标签: android kotlin android-context

我正在尝试使用applicationContext初始化连接管理器。 我希望用户发送活动上下文,然后我将从中获取applicationContext。但是,我无法确定用户不会直接发送applicationContext。我已经写了一个if else语句来初始化connectivityManager但我想知道是否有更好的方法来做到这一点。有letelvis运算符的任何东西可能吗?

/**
 * if user has passed application Context, we use it to get system service,
 * else we get applicationContext from it and use that instead.
 */
private val connectivityManager = if (context.applicationContext == null)
    context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
else
    context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

1 个答案:

答案 0 :(得分:2)

private val connectivityManager = 
    context.run { applicationContext ?: this }.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

但我认为你可以将其转移到扩展功能

private val connectivityManager: ConnectivityManager = 
    context.findSystemService(Context.CONNECTIVITY_SERVICE)

inline fun <reified T> Context.findSystemService(val serviceTag: String): T = 
    (applicationContext ?: this).getSystemService(serviceTag) as T