Java – kotlin: generic method and for loop request iterator ()
This is a simple generic method, and passing args in forgs to the for loop causes an error:
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 let it iterate over char [] and the value of the array
Solution
The for loop in kotlin works by convention. It statically looks for an operator member named iterator. The operator member must return something that can be iterated, that is, something that contains operator and hasnext in turn
The operator modifier on these members needs to specify whether the member satisfies certain conventions, i.e. iteration conventions
Since args is of type T and has no iterator member in every possible type T, it cannot be iterated easily
However, you can provide an additional parameter to printme, which knows how to get the iterator from the T instance, and then use it to get the iterator and iterate it:
fun main(args: Array<String>) { val arr: IntArray = intArrayOf(1,'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. () – > iteration & lt * gt; Is a type representing function with receiver Instances of this type can be called on t as if they were its extensions
The returned iterator itself is an operator extension function iterator < T > Iterator () = this, which returns only iterators, thus allowing for loops to iterate over iterators