In a when block I have a lot of code like that: ``...
# getting-started
m
In a when block I have a lot of code like that:
Copy code
"-" -> 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:
Copy code
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
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
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
btiasD!
1