https://kotlinlang.org logo
#random
Title
# random
s

Sam

01/24/2023, 3:58 PM
Today I wrote this code:
Copy code
if (iterator.hasNext()) doSomethingWith(iterator.next()) ?: return null else return null
I have very mixed feelings about
return null else return null
😄
😀 1
e

ephemient

01/24/2023, 4:25 PM
you could do
Copy code
(if (iterator.hasNext()) doSomethingWith(iterator.next()) else null) ?: return null
or if it's an iterator of non-null,
Copy code
iterator.takeIf { it.hasNext() }?.let { doSomethingWith(it.next()) } ?: return null
I've thought
Iterator<T>.nextOrNull()
could be useful on a handful of occasions, but not very often
1
s

Sam

01/24/2023, 4:34 PM
takeIf { it.hasNext() }
is a nice idea, I'll have to have a play with that 👌
j

janvladimirmostert

01/24/2023, 9:53 PM
‼️ 4
sad panda 3
e

ephemient

01/24/2023, 10:01 PM
`?: throw`/`checkNotNull`/`requireNotNull` can be better than
!!
in some situations, such as when providing a detailed message, because Kotlin doesn't. https://youtrack.jetbrains.com/issue/KT-6989 but that doesn't apply to that code snippet 😞
s

Sam

01/24/2023, 10:26 PM
And maps have
getValue
too, but I'd have to check how useful its message is. I've never been quite sure whether it's actually intended to be used at all on non-defaulted maps...
e

ephemient

01/24/2023, 10:29 PM
getValue
throws
NoSuchElementException("Key $key is missing in the map.")
, so it is useful
🐕 1
5 Views