4

Is it possible to set the value of a variable to a method, where the method is on a Companion object and has a type parameter? Something like the following:

class A {
    companion object B {
        fun <T>foo(n: T)  { }
    }
}

val b = A.B::foo<T>
Julian A.
  • 10,928
  • 16
  • 67
  • 107
  • Not exactly a duplicate, but related: https://stackoverflow.com/questions/37629644/how-to-pass-a-type-parameter-to-a-generic-class-constructor-reference – kabuko Jan 19 '18 at 01:00

1 Answers1

4

No, there's no representation for generic function references in the type system. For instance, it does not have quantified types, which could represent the function you're trying to reference in a form like forall T . (T) -> Unit.

You can only take a non-generic reference to a generic function, and for that you have to provide the concrete types in the expected type (it's taken from where the reference is assigned or passed), for example, this will work:

class A {
    object B {
        fun <T> foo(n: T) { }
    }
}

val b: (Int) -> Unit = A.B::foo // substitutes T := Int
val c: (String) -> Unit = A.B::foo // T := String here

fun f(g: (Double) -> Unit) = println(g(1.0))
f(A.B::foo) // also allowed, T := Double inferred from the expected type
hotkey
  • 140,743
  • 39
  • 371
  • 326