Home > Back-end >  looping through customViews in a viewgroup, as that custom view
looping through customViews in a viewgroup, as that custom view

Time:04-28

I have a grid full of a custom view I've created. I can easily loop through it using for (item in grid) {} and I can then set things such as onClick etc. However, my custom View has it's own functions which I would like to access and kotlin has no way of knowing item is always going to be type CustomView (It definitely will be though) so I wanted to do something like:

for (item in grid as CustomView) {
    item.customFun()
}

I must be missing something here because it gets marked with this cast can never succeed, but I just need kotlin to know this will always be a CustomView

CodePudding user response:

Here for (item in grid as CustomView), you've used grid as CustomView that is trying to cast the grid as a CustomView, which is why the compiler is complaining this cast can never succeed.

You have to cast the item inside the body of the for loop

for (item in grid) {
    (item as CustomView).customFun()
}

as is an unsafe cast operator, which would throw exception when item won't be an instance of CustomView. There you can use is for type checking.

for (item in grid) {
    when(item) {
        is CustomView -> item.customFun()
    }
}
  • Related