3

when a function declares a type parameter:

fun <T> typedFunction(value: T, option: Option<T>) { ... }

how should I call the raw un-typed typedFunction in kotlin?

why?

In java I have:

// This is a method in an external library. I can not change it.
void <T> typedFunction(T t, Option<T> o) { ... }

// This is my code. optionsValues contains many types
// such as Option<Integer>, Option<String>, and ...
Map<Option<?>, ?> m = readAndParseFromConfigFile();
for (Map.Entry<Option<?>, ?> e : m.entrySet()) {
   // The cast does the trick!
   // I know my code is safe, I can tell the compiler to back off.
   typedFunction((Option) e.getKey(), e.getValue());
}

Because typedFunction declares a type named T and binds both its parameters to this declared type, and on the call site I'm looping over multiple values whose exact type is unknown (but known to be safe, both parameters conform to same type) I can not call the typedFunction the way intended. I have to cast it into a raw type.

How can achieve the same in kotlin?

What IntelliJ does:

This is how IntelliJ converts my code:

val m: Map<Option<*>, *>? = ...
for ((key, value) in m!!) {
    typedFunction<*>(key, value)
    //           ^^^  ERROR!!
}

But it gives an error afterwards: "Projections are not allowed on type arguments of functions and properties"

2
  • 1
    Can’t you just let the compiler infer? typedFunction(...)
    – s1m0nw1
    Jan 11, 2018 at 12:47
  • @s1m0nw1 no, they are inferred as Option<*> and Any which are incompatible
    – hkoosha
    Jan 11, 2018 at 13:27

1 Answer 1

2

Since Kotlin does not have raw types and does not provide a star-projection equivalent for function calls, there should be a concrete type for T.

You can make an unchecked cast of the Option<*> argument to Option<Any>, so that T becomes Any:

val m: Map<Option<*>, *>? = ...

for ((key, value) in m!!) {
    @Suppress("unchecked")
    typedFunction(key as Option<Any>, value) // inferred T := Any
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.