https://kotlinlang.org logo
#korge
Title
# korge
j

jeff

01/30/2021, 7:44 PM
Is there any mechanism to access a component of particular type (e.g.
MyCustomComponent : Component
) that is attached to a view IFF it is already attached (i.e. don't create one if it doesn't exist)?
I tried this code which works great in JVM but throws a ClassCastException in Kotlin/JS
Copy code
inline fun <reified T : Component> BaseView.getComponentOrNull(): T? {
    return getOrCreateComponentOther<T> {
        return null
    }
}
d

Deactivated User

01/31/2021, 6:18 PM
Do you mean, any type? You can use
getOrCreateComponentUpdate
,
getOrCreateComponentMouse
... Initially it was just
getOrCreateComponent
but was converted into that to improve performance in K/N. What's your use case / why do you need the method you want to write?
j

jeff

01/31/2021, 6:26 PM
Yeah, any type. I have a custom component that handles some logic & animation. I'd like to be able to "clear" it (i.e. find & detach any component of that type from a given view) without having to maintain a reference to each one.
Technically I could do that with
getOrCreateComponent
but in the case where none previously existed I'd end up constructing one only to immediately throw it away
Open to suggestions, including better ways to structure a game if this seems to you like a weird thing for someone to want to do 🙂
d

Deactivated User

01/31/2021, 6:39 PM
So the component is not an standard component, right? It is something you use internally?
j

jeff

01/31/2021, 6:39 PM
correct, just extends
Component
(not, say,
UpdateComponent
)
d

Deactivated User

01/31/2021, 6:47 PM
We should definitely rework the component part to have only one method. The current API is weird, but was designed to avoid a performance hit on Kotlin/Native, so as long as they improve it, we will be able to simplify it again. There is a
getOrCreateComponentOther
We can just add variants like
getComponentOrNull
you can even make a PR to add them: https://github.com/korlibs/korge-next/blob/721d78c9ae1c7ce5c3a5b999a30eaeca46c93a8[…]rge/src/commonMain/kotlin/com/soywiz/korge/baseview/BaseView.kt Can you make a PR adding those
getComponent*OrNull
methods? Alternatively,
View
implements the
Extra
interface, that support adding extrinsic properties without weak maps, so you can attach stuff there yourself and externally define your own code for a custom component system. But well, as said, PRs are welcome 🙂
j

jeff

01/31/2021, 6:50 PM
More than happy to add a PR. The version I have seems to run afoul of Kotlin/JS's runtime type checking, since it throws a CCE there (but not on JVM). If I can figure out why and fix it, I'll submit it.
👍 1
I'll also look into Extra, that seems promising
thanks!
2 Views