Consider the following attempt to produce a forEach()
method that recursively traverses the given View hierarchy and consume
-s all View(s) of the specified type T:
private inline fun <reified T: View> forEach(view: View, noinline consume: (T) -> Unit) {
forEachEx(T::class.java, view, consume)
}
private fun <T: View> forEachEx(c: Class<T>, view: View, consume: (T) -> Unit) {
if (c.isInstance(view))
consume(view as T)
if (view is ViewGroup) {
view.children.forEach { childView ->
forEachEx(c, childView, consume)
}
}
}
The call to forEachEx(T::class.java, view, consume)
fails to compile with this somehow cryptic message:
None of the following substitutions
(Class<CapturedTypeConstructor(out Int)>,View,(CapturedTypeConstructor(out Int)) -> Unit)
(Class<View>,View,(View) -> Unit)
(Class<T#2 (type parameter of com.xyz.MainActivity.forEach)>,View,(T#2) -> Unit)
can be applied to
(Class<out Int>,View,(T#2) -> Unit)
Explain this to me, please.
And how to get a forEach function that would be nicely called like this:
forEach<TextView>(topView) { /* do something with each TextView */ }