'Kotlin - Conditional method name with same parameters (mitigation of code duplication)

Let's consider this code examples in Kotlin:

if (isFooBar)
    method1(arg1, arg2, arg3)
else
    method2(arg1, arg2, arg3)

// Or larger example
when(enumBar) {
    VALUE_A -> method1(arg1, arg2, arg3)
    VALUE_B -> method2(arg1, arg2, arg3)
    VALUE_C -> method3(arg1, arg2, arg3)
    VALUE_D -> method4(arg1, arg2, arg3)
    else -> method5(arg1, arg2, arg3)
}

Can this be improved somehow to reduce code duplication? I imagine something like:

(if (isFooBar) method1 else method2)(arg1, arg2, arg3)


Solution 1:[1]

If the methods all have the same return type and parameter types, you can first select the right method to call and assign that to a val like this, using the function reference syntax.

val methodToCall = 
    if (isFooBar) ::method1 else ::method2
    
methodToCall(arg1, arg2, arg3)

In the case of when:

val methodToCall = when (someEnum) {
    A -> ::method1
    B -> ::method2
    C -> ::method3
    else -> ::method4
}
methodToCall(arg1, arg2, arg3)

Type inference will work correctly, provided that the methods do have the same parameter types and return types.


Technically, you don't need the methodToCall variable, and can just do:

(if (isFooBar) ::method1 else ::method2)(arg1, arg2, arg3)

but I don't think this is very readable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sweeper