Recently had some discussion about whether the !! should be used in kotlin code. One opinion is it should not be used at all, because it is a bad practice with kotlin and increase the risk of crash.
Another opinion feels using !! is not a absolutely bad thing, as long as you know that nullable data should not be null at the place under any known condition, !! is just a safety guard there (if it is unexpectedly become null at where it should not be the !! will caught it and raise concern then it definitely needs to be investigated). It should not consider using !! is one cause of crash.
Does anyone have opinion against or vor using the !! (not blindly use it)?
two samples below, dont see the dataCount_2 would be better, or?
var data: List<Data>? = null // it will be set before calling the two dataCount()
fun dataCount_1() : Int {
return if (data!=null && data!!.isNotEmpty()) data!![0].count else 0
}
fun dataCount_2() : Int {
data?.let { dataList ->
if (dataList.isNotEmpty()) {
return dataList[0].count ?: 0
}
}
return 0
}
In this case, there are multiple idiomatic ways to express the idea without using !!
, so it's definitely preferable to not use it. Here's what I would do (using the orEmpty function added in Kotlin 1.3):
fun dataCount() = data.orEmpty().firstOrNull()?.count ?: 0
In other cases, it may not be as easy, so there is no absolute rule saying that !! must never be used. However, in our experience, a significant percentage of uses of !! in IntelliJ and Kotlin codebases end up being reported as runtime exceptions from our users.