I've got a class `FunctionRef<F : Function<*>>(fun...
# general-advice
c
I've got a class
FunctionRef<F : Function*>(func: F)
. How do I make it so instantiating it with a
KFunction1
makes
F := Function1
, where it's only usable as a direct subtype of
Function
instead of as a
KFunction
? Can you do this with generics? For example:
Copy code
class FunctionRef<F : Function*>(val func: F)

// Desired:
val x: FunctionRef() - Unit> = getFunctionRef(::foo)
// Actual:
val x: FunctionRef<KFunction0Unit> = getFunctionRef(::foo)
I'm essentially trying to force both an upper and lower bound on the generic, but I don't know how you'd do this.
y
You're not gonna love this solution, but it works
Copy code
class FunctionRef<F : Function<*>>(val func: F)

fun <F: Function<*>> getFunctionRef(func: F, unit: Unit = Unit) = FunctionRef(func)

@Deprecated("Please create a new overload that takes `FunctionN`, or cast your function as such", level = DeprecationLevel.ERROR)
fun <F: KFunction<*>> getFunctionRef(func: F, unit: Unit = Unit) = FunctionRef(func)

fun <R> getFunctionRef(func: KFunction0<R>) = FunctionRef<Function0<R>>(func)
fun <A, R> getFunctionRef(func: KFunction1<A, R>) = FunctionRef<Function1<A, R>>(func)

fun foo() {}

// works
val x: FunctionRef<() -> Unit> = getFunctionRef(::foo)
// doesn't
val y: FunctionRef<KFunction0<Unit>> = getFunctionRef(::foo) // Initializer type mismatch: expected 'FunctionRef<KFunction0<Unit>>', actual 'FunctionRef<() -> Unit>'.

fun foo2(a: String, b: Int) {}

val z = getFunctionRef(::foo2) // Please create a new overload that takes `FunctionN`, or cast your function as such.
you need an overload that takes
KFunctionN
for every N, and returns the proper value To smooth over such a migration, I added a deprecated overload for any not-covered `KFunction`s
c
Makes sense, it just takes specializing the method for each subclass. I wonder if there's a way to automate that with an FirFunctionCallRefinementExtension...
y
If you're going that route, you could probably use that to modify the return type directly