0
votes

Does someone know what goes I'm doing wrong here?

// ...
val alphabet = ('a'..'z').toList()
val str = "testing"
val arr = str.split("")

for (char in arr) {
    var i = alphabet.indexOf(char) // Throws Error!
    //    ...
}

The indexOf-method results in "Error:(10, 26) Kotlin: Type inference failed. The value of the type parameter T should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly."

I have tried to "var i: Int = alphabet.indexOf(char)" and "alphabet.indexOf(char) as Int". The same result ...

What's the issue here?

1
Instead of splitting with empty string, you can just call toList() on to string, or even iterate over original string instead, cuz String itself implements CharSequence so should be iterable with Char datatype. for (char in str) {} - Animesh Sahu
Awesome. Thanks a lot. - michael.zech

1 Answers

4
votes

I believe that your problem is that you think that the variable char contains a Char value. If that were the case, then it would make sense for indexOf to be accepting a Char value and then finding the location of that character in a list of characters (List<Char>) on which the method is being called.

But str.split() is returning a List<String>, not a List<Char>, and so char is a String. So you are asking the indexOf method to tell you the location of a String in a list of characters (List<Char>). That doesn't make sense. That's the basis of the problem. Exactly how that translates to the error you're getting from the Kotlin compiler, I'm not sure.

To make it clear, this line produces the same error:

var i = alphabet.indexOf("c") // Throws Error!

but the compiler likes this line just fine:

var i = alphabet.indexOf('c') // No Error!!!