https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Marc Fearby

02/03/2023, 2:17 AM
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

Vampire

02/03/2023, 2:47 AM
That's actually not a
KFunction<String>
, but a
KFunction1<MyInterface, String>
and you call it with
.call(theInstanceHere)
K 1
👍 1
m

Marc Fearby

02/03/2023, 3:05 AM
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

Marc Fearby

02/03/2023, 3:06 AM
If something doesn’t work/import in IJ, I tend to assume I’m doing something wrong and accept it 🙂
👌 1
v

Vampire

02/03/2023, 3:06 AM
It's age is only 6 years 😄
😅 1
🫣 1
3 Views