If I have a `KFunction<String>` variable, i...
# getting-started
m
If I have a
KFunction<String>
variable, is there a way to invoke it on a class? I have an interface with two functions, both of which return a string, and I’d like to choose between one or the other, and pass it to another function to invoke on objects which implement that interface (using the reference to the function name). Is this possible? Thank you.
I’m getting the
KFunction<String>
reference like this:
val summaryFunction = if (someType == "Something") MyInterface::toSummary else MyInterface::toOtherSummary
And I want to be able to invoke that function reference instead of the hard-coded toSummary() in the example below:
if (someObject == null) otherObject.toSummary()
else """
The original details are:
${someObject.toSummary()}
and the new details are:
${otherObject.toSummary()}
""".trimIndent()
v
That's actually not a
KFunction<String>
, but a
KFunction1<MyInterface, String>
and you call it with
.call(theInstanceHere)
K 1
👍 1
m
Thanks Björn. The type hint in IntelliJ said it was a KFunction1 but wouldn’t let me import it, so I removed the 1 and it seemed happy to import that (but obviously wasn’t what I wanted). I can import it manually and it works a treat. Thank you very much 🙂
m
If something doesn’t work/import in IJ, I tend to assume I’m doing something wrong and accept it 🙂
👌 1
v
It's age is only 6 years 😄
😅 1
🫣 1