#Make function return single element or array of elements based on parameter type
1 messages · Page 1 of 1 (latest)
Detected code, here are some useful tools:
<@&1008423204219531294> please have a look, thanks.
Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
T : Base> createInstance(single: Boolean): T {
return if (single) {
ChildA() as T
} else {
arrayOf(ChildA(), ChildB()) as T
}
}
fun main() {
val singleInstance = createInstance<ChildA>(true)
println(singleInstance)
val multipleInstances = createInstance<Base>(false)
multipleInstances.forEach { println(it) }
}
Output:
ChildA@4f023edb
ChildA@7cc355be
ChildB@6a9e6d8e
no, just return a list or array of 1 element
In java, you would create overloads
Can only do covariant return type overloads
so entity.getComponent(Transform) -> single component because entities can only have 1 transform
entity.getComponent(FireEffect) -> array of multiple components because you can stack spell effects
is impossible to do ?
oh shoot can't I just overload the method?
No if your parameters are different you can
the type needs to be different
Yes
so I will probably make an intermediary base class
inheriting from Component
that just serves to make it different
But fire effect and transform are different
abstract class Component
class Plural : Component()
class Singular : Component()
fun f(x: Plural)
fun f(x: Singular)
class Transform : Singular
class SpellEFfect : Plural
Detected code, here are some useful tools:
can I do this?
the classes don't really do anything except for type discrimination
so maybe i should use interfaces instead
Interfaces are perfect.for this
even if no methods or properties exist on the interface
they are just nominal constructs
that legit to do?