#Make function return single element or array of elements based on parameter type

1 messages · Page 1 of 1 (latest)

gritty patrol
#

Is something like this possible in kotlin

abstract class Base

class ChildA : Base()
class ChildB : Base()

fun <T: Base> f(x: KClass<T>) {
    if x is ChildA
        return 1
    else
        return [1,2,2]
}

it is possible in typescript.

vague patrolBOT
#

<@&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

umbral scarab
#

no, just return a list or array of 1 element

trim cobalt
umbral scarab
#

Can only do covariant return type overloads

gritty patrol
#

oh shoot can't I just overload the method?

umbral scarab
#

No if your parameters are different you can

gritty patrol
#

the type needs to be different

umbral scarab
#

Yes

gritty patrol
#

so I will probably make an intermediary base class

#

inheriting from Component

#

that just serves to make it different

umbral scarab
#

But fire effect and transform are different

gritty patrol
#
abstract class Component

class Plural : Component()


class Singular : Component()

fun f(x: Plural)
fun f(x: Singular)

class Transform : Singular

class SpellEFfect : Plural
vague patrolBOT
gritty patrol
#

the classes don't really do anything except for type discrimination

#

so maybe i should use interfaces instead

umbral scarab
#

Interfaces are perfect.for this

gritty patrol
#

they are just nominal constructs

#

that legit to do?

umbral scarab
#

sure, those are called marker i nterfaces

#

But if you can dump your stuff on github or something I could give you some more overall design pointers

#

Going off of small examples like this is hard

#

Because this is architecture territory

hot ginkgo
#

It is possible

#
public static <T, C extends Component<T>> T getComponent(Class<C> clazz) {

}