如何在Kotlin中优化代码?

时间:2018-05-01 13:12:26

标签: android kotlin

代码A非常简单,我可以在Kotlin中优化代码B吗?

代码A

val pendingIntent = if (isServer)
        PendingIntent.getService(myContext, 0, myIntent, 0)
    else
        PendingIntent.getActivity(myContext, 0, myIntent, 0)

代码B

var builder: NotificationCompat.Builder? =null

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    val importance = NotificationManager.IMPORTANCE_DEFAULT
    val notificationChannel = NotificationChannel("ID", "My", importance)
    notificationManager.createNotificationChannel(notificationChannel)
    builder = NotificationCompat.Builder(applicationContext, notificationChannel.id)
} else {
    builder = NotificationCompat.Builder(applicationContext)
}

2 个答案:

答案 0 :(得分:1)

   var builder: NotificationCompat.Builder = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

                val importance = NotificationManager.IMPORTANCE_DEFAULT
                val notificationChannel = NotificationChannel("ID", "My", importance)
                notificationManager.createNotificationChannel(notificationChannel)
                NotificationCompat.Builder(applicationContext, notificationChannel.id)
            } else {
                NotificationCompat.Builder(applicationContext)

            }

答案 1 :(得分:1)

代码A很好。

可以通过使builder成为非可空的val而不是可空的var来简化代码B,方法是使其成为if表达式的结果(就像在代码A中一样)。此处也可以推断builder的类型,您可以选择将其关闭。此外,在第一个if块内,您可以直接使用importance值使其更清晰,而不是将其声明为值(仅在一个地方使用)。

val builder = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    val notificationChannel = NotificationChannel("ID", "My", NotificationManager.IMPORTANCE_DEFAULT)
    notificationManager.createNotificationChannel(notificationChannel)
    NotificationCompat.Builder(applicationContext, notificationChannel.id)
} else {
    NotificationCompat.Builder(applicationContext)
}

除此之外的任何事情(在if块中使用alsoapply)我认为在这种情况下不太清楚。我不是非常喜欢那里中间notificationManager的电话,但我不是Android开发者,也不确定这种副作用是否是惯用的。