0

I'm trying to perform the following line in Kotlin:

var str: KFunction<String> = String::toUpperCase

But compiler says:

Overload resolution ambiguity. All these functions match. public inline fun String.toUpperCase(): String defined in kotlin.text public inline fun String.toUpperCase(locale: Locale): String defined in kotlin.text

I thought that writing KFunction should overcome the ambiguity since not writing nothing before the String in KFunction means that the KFunciton shouldn't get parameters and only return a String (which compatible with the function that is defined in kotlin.text package, but it seems that the compiler want some more info. I'm also trying the following assignment:

    var str: KFunction<java.util.Locale,String> = "some Word"::toUpperCase

And getting additional error saying that:

One type argument expected for interface KFunction

If I will use a method that isn't overloaded (like *toString) , So everything works. For Example:

var str: KFunction<String> = String::toString

What Am I missing here?

DorVak
  • 297
  • 2
  • 9
  • What are you trying to achieve with this exactly? What do you expect to be assigned on str – georkost Nov 28 '20 at 12:02
  • I have changed the example in the question to *String:: toUpperCase* .. I'm expecting that I will be able to use str varibale to run a function that get a String/or Locale and perform the toUpperCase that returns a String . If toUpperCase wasn't overloaded and instead of toUpperCase I will write toString for example so everything works – DorVak Nov 28 '20 at 12:22
  • @IR42, did your try it mate? i'm still getting the old erorr + *"Unresolved reference: KFunction1"* – DorVak Nov 28 '20 at 12:43
  • @IR42, ok thanks. I was surprised that alt + enter didn't import it automatically. Can you tell me please what is the type the should be at left side of the assignment if i'm trying to get function reference that's bound to an instance: *val whatShouldIWriteVariable = "abcd"::toUpperCase* ? – DorVak Nov 28 '20 at 12:51
  • actually, it is better to use [function types](https://kotlinlang.org/docs/reference/lambdas.html#function-types) syntax, `var str: (String) -> String = String::toUpperCase` and `() -> String` for instance method reference – IR42 Nov 28 '20 at 13:02
  • @IR42, I see.. Because it's impossible to use KFunction to solve the ambiguity in the case I have described in my previous comment? *var str: KFunction = "das"::toUpperCase* – DorVak Nov 28 '20 at 13:14
  • 1
    KFunction is intended for reflection. You would typically get a reference to a KFunction by using a KClass, listing its members, and picking one out of the list by name. – Tenfour04 Nov 29 '20 at 13:16

1 Answers1

0

You should use

val str: KFunction2<String,Locale, String> = String::toUpperCase
dstibbe
  • 1,589
  • 18
  • 33