Using List
or Sequence
Your best bet would be converting the iterator to Sequence
, where you can call the find()
method.
val index = headerRow
.asSequence() //To sequence
.find { "IP" == formater.formatCellValue(it) }
Using Iterator
If for some kind of reason you can't use List
I don't really think there is a prettier way (of course there always can be). But if your main problem is that you get a type of Any
from your let
construction you can always just cast the found index with as Int
or if you are not sure that the index will be of type Int
, use as? Int
, which will return nullable value of Int:
val ipColumn = headerRow.cellIterator().let {
it.forEach { cell ->
if ("IP" == formater.formatCellValue(cell))
return@let cell.columnIndex
}
} as Int //This returns `Int`
Using extensions
If you still don't like any of those 2 options. Or if you want to use the code in more places. You can create yourself an extension function/method:
fun Row.find(predicate: (Cell) -> Boolean): Cell?
= cellIterator().asSequence().find(predicate) //Put this code anywhere is your code...
After you put these lines anywhere in your code, you can simply call:
val index = headerRow
.find { "IP" == formater.formatCellValue(it) }?
.columnIndex //This returns optional Int
Please note, that I did not compile any of these examples, I do not have the necessary library for that!