user2498079
user2498079

Reputation: 3002

Passing a method as a reference with default parameters

I've a class where I'm passing a static method A of another class to a method M with reference. The method A has a default argument however due to the method signature of the method M, it's forcing me to provide all the arguments even the default argument.

I don't want to pass the default argument since some classes with method A don't have/require the argument that's setup as default argument in method A of all the classes.

class MyClass1 : BaseClass {

  companion object {
       fun A(obj1 : Type1, obj2 : Type2, obj3 : Type3? = null) { //implementation }
  }
}

class MyClass2 : BaseClass {

  companion object {
       fun A(obj1 : Type1, obj2 : Type2) { //implementation }
  }
}

class ClassX {

    fun M(obj1 : Type1, obj2: Type2, obj3 : Type3? = null, A : (Type1, Type2, Type3) -> TypeX) {
        //implementation
    }
}

MyClass1 method A can take all the arguments however Since MyClass2 doesn't have obj3 in its method A, I can't pass Method A as a reference to this method M anymore.

Is there a way to set default argument for method reference in Method M?

Upvotes: 0

Views: 296

Answers (1)

Tenfour04
Tenfour04

Reputation: 93609

No, functional parameters cannot be defined as having default parameter values. They must be fully concrete. When you pass MyClass1::A to this function, it is not passing a function that has default parameters, but rather it is selecting the implicit, specific overload of A that fits the signature.

Upvotes: 2

Related Questions