Venkatesh_J
Venkatesh_J

Reputation: 63

Kotlin: For-loop range must have an 'iterator()' method

If I use var charSet = 1..10 it works, but when I am using the below code, I'm getting this error.

var charSet = "A".."Z"
for (value in charSet) {    
  println("$value")  
}

For-loop range must have an 'iterator()' method.

Please let me know how to resolve this.

Upvotes: 2

Views: 6103

Answers (3)

Alf Moh
Alf Moh

Reputation: 7437

To declare a string, we use double quotes and to declare a character, we use single quotes. You can iterate through characters and not strings. When you change your quotes to single, your code will run perfectly.

Upvotes: 2

Sasi Kumar
Sasi Kumar

Reputation: 13358

Its giving current output.Change your double quotes into single quotes

    var charSet = 'A'..'Z'
    for (value in charSet) {
        println("$value")
    }

Upvotes: 4

Mibac
Mibac

Reputation: 9458

charSet is a ClosedRange<String> and that type doesn't have iterator() function (but ex. IntRange does). You can either change your range to 'A'..'Z' or create an extension function ClosedRange<String>.iterator() which would return a Iterator. The error should then go away

Upvotes: 5

Related Questions