Today I wrote this code: ```if (iterator.hasNext()...
# random
s
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
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
takeIf { it.hasNext() }
is a nice idea, I'll have to have a play with that 👌
j
‼️ 4
sad panda 3
e
`?: 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
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
getValue
throws
NoSuchElementException("Key $key is missing in the map.")
, so it is useful
🐕 1