Can't iterate over input string [SOLVED] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 9

Can't iterate over input string [SOLVED]

So I'm learning Kotlin for fun but I got stuck. I want to write code that takes an input word and prints its letters on separate lines. I tried fun main(args: Array<String>) { var word = readLine() for (letter in word) { println(letter) } } but I get error: not nullable value required to call an 'iterator()' method on for-loop range I can print an input word, and I can print a word letter by letter, just not an input word letter by letter. I figured out a workaround by creating a new string by adding "" to the input string, but that shouldn't be necessary (should it?) See these 4 codes. Any ideas? Yes I used the search bar :\ https://code.sololearn.com/c82A163A15A2 https://code.sololearn.com/cPdWINY0Bkx1 https://code.sololearn.com/cA21a100a228 https://code.sololearn.com/cA8a4a8A0a99

7th Mar 2021, 7:42 AM
David Ashton
David Ashton - avatar
5 Answers
+ 9
The readLine() function returns the type `String?`. The type `T?` signifies that `T` is a nullable type, that is, null can be assigned to that type. Read more here https://kotlinlang.org/docs/null-safety.html This means that the readLine() function may return either a valid string or null. Check out the following link for when it returns null: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/read-line.html: When you try to iterate on a nullable value, as you are doing in your code, the compiler gives error saying that a not nullable value is required for calling the iterator() method. So to convert a nullable value to a not nullable value, you can use the !! operator. Using !! on type `T?` returns `T` if the value is not null, else it throws the NullPointerException. Read about it here https://kotlinlang.org/docs/null-safety.html#the-operator Your fixed code https://code.sololearn.com/cb9S5h33xvKn/?ref=app
7th Mar 2021, 8:04 AM
XXX
XXX - avatar
+ 6
David Ashton We have to use !! after readLine() when dealing with user input because there maybe possibility to have null value in user inputs. Maybe I am wrong but I found this solution. https://code.sololearn.com/clYzaq5mos3F/?ref=app
7th Mar 2021, 8:04 AM
A͢J
A͢J - avatar
+ 6
David Ashton I found other ways to iterate string if you don't want to use !! https://code.sololearn.com/cLBfwbOE7Fy3/?ref=app
7th Mar 2021, 8:47 AM
A͢J
A͢J - avatar
+ 4
Thanks I Am AJ ! and XXX ! Interesting that you can print but not iterate without !! after readLine().
7th Mar 2021, 8:11 AM
David Ashton
David Ashton - avatar
+ 4
Dynamite! Thanks I Am AJ ! I can see I'm only scratching the surface.
7th Mar 2021, 8:51 AM
David Ashton
David Ashton - avatar