This is a simple generic method,and passing the values the args in for loop is causing an error saying:
for-loop range must have and iterator() method
fun main(args: Array<String>) {
val arr: IntArray = intArrayOf(1,2,3,4)
val charA: CharArray = charArrayOf('a','b','c','d')
printMe(arr)
printMe(charA)
}
fun <T>printMe(args: T){
for (items in args){
println(items)
}
}
how do i make it iterate throught the values for both char[] and array
for-loop in Kotlin works by convention, looking statically for an operator member named iterator which must return something that can be iterated, i.e. something that has in turn operator members next and hasNext.
operator modifier on such members is required to specify that the member is to satisfy some convention, namely the iteration convention.
Since args is of type T and there is no iterator member in every possible type T, it can't be iterated readily.
However you can provide an additional parameter to printMe, which knows how to get an iterator out of an instance of T, and then use it to obtain an iterator and iterate it:
fun main(args: Array<String>) {
val arr: IntArray = intArrayOf(1,2,3,4)
val charA: CharArray = charArrayOf('a','b','c','d')
printMe(arr, IntArray::iterator)
printMe(charA, CharArray::iterator)
}
fun <T> printMe(args: T, iterator: T.() -> Iterator<*>) {
for (item in args.iterator()) {
println(item)
}
}
Here T.() -> Iterator<*> is a type which denotes a function with receiver. Instances of that type can be invoked on T as if they were its extensions.
This snippet works because the iterator returned has itself an operator extension function Iterator<T>.iterator() = this which just returns that iterator, thus allowing to loop through the iterator with a for-loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With