Is there a better way of writing this without usin...
# codereview
e
Is there a better way of writing this without using scope functions, which I haven't introduced yet?
l
How about:
Copy code
fun readInt() : Int { 
    return generateSequence { readLine() }
        .mapNotNull { it?.toIntOrNull() }
        .first()
}
e
Copy code
.mapNotNull { ... }.first() == .firstNotNullOf { ... }
but part of the loop seems like a bad idea. if
readLine()
returns null, that means you're at EOF and it will continue returning null
if you use the
readln()
function, it'll instead throw an exception on EOF instead
k
And in any case
readLine()
should be regarded as deprecated - if you still want its behaviour (instead of
readln()
), call
readlnOrNull()
which is a much more descriptive name.
e
Thanks for all the feedback. Why should
readLine()
be regarded as deprecated? @Klitos Kyriacou
I could be mistaken, but it doesn’t look like any of the alternatives re-prompt the user.
k
readlnOrNull()
does exactly the same thing as
readLine()
(so you can do a global search and replace) but has a more descriptive name.
If you haven't introduced scope functions yet, then solutions using
mapNotNull
etc would presumably also be too advanced at this stage. I would keep your function definition as it is, but replace
readLine()?.toIntOrNull()
with
readln().toIntOrNull()
.
If you use
readln()
instead of
readlnOrNull()
, it will throw an exception if you enter ^D (or ^Z for those who use Windows), which is probably better than an infinite loop.
e
exactly. instead of getting an infinite loop when null is returned from `readLine()`/`readlnOrNull()`, it would be much better to
readln()
and abort. that's what I was trying to hint at earlier