Kotlin replace isEmpty () and last () with lastOrNull () in collection

I would like to use something like the code below, but I think there should be a nicer solution using lastOrNull()

instead of using isEmpty

andlast()

data class Entry(val x: Float, val y: Float)

      


var entries: MutableList<Entry> = ArrayList()
if(some) {
  entries.add(Entry(100f, 200f)
}
val foo = (if (entries.isEmpty()) 0f else entries.last().y) + 100f

      

Is there a better way for example entries.lastOrNull()?.y if null 0f

?

+3


source to share


2 answers


you can use Kotlin elvis operator ?:

like:

//   if the expression `entries.lastOrNull()?.y` is null then return `0f` 
//                                  v              
val lastY = entries.lastOrNull()?.y ?: 0f

      



for the expression in your code above, you can use safe-call ?.let

/ ?.run

to make your code clearer, for example:

//val foo = if (entries.isEmpty()) 0f else entries.last().y + 100f else 100f

//             if no Entry in List return `0F`  ---v
val foo = entries.lastOrNull()?.run { y + 100 } ?: 0F 
//                            ^--- otherwise make the last.y + 100  

      

+6


source


If I understand you correctly, this will do the job:



val foo = if (entries.isEmpty()) 0f else entries.lastOrNull()?.y ?: 0f + 100f

      

0


source







All Articles