https://kotlinlang.org logo
Title
m

Martin Barth

11/08/2021, 10:23 AM
In a when block I have a lot of code like that:
"-" -> if (aggregate is Minus) Minus(*aggregate.expressions, nextExpression) else Minus(aggregate, nextExpression)
                        "+" -> if (aggregate is Plus) Plus(*aggregate.expressions, nextExpression) else Plus(aggregate, nextExpression)
....
I wanted to make that easier, but i am failing. My Idea was something like this:
private inline fun <reified T> myIdea(aggregate: InfixExpression, nextExpression: Expression): T = if (aggregate is T) 
            T(*aggregate.expressions, nextExpression)
        else
            T(aggregate, nextExpression)
using the Type T as a Constructor does not work. Any advice?
m

Michael de Kaste

11/08/2021, 10:38 AM
make a static 'of' function that implies T.of(...) -> T on an class parent of both Minus and Plus or use invoke constructors using reflection
v

Vampire

11/08/2021, 10:38 AM
As the compiler does not know which type
T
will be, it cannot know which constructors would exist, so I don't think this is possible directly. You need to resort to reflection. Use
T::class.constructors
or
T::class.java.getConstructor(type1, type2)
to find the constructor you want to invoke and then call it.
c

Chris Black

11/09/2021, 4:11 PM
btiasD!
1