bschandramohan
bschandramohan

Reputation: 2006

Calling generics method argument in kotlin

fun <T> doSum(a: T, b: T) : T {
    val result : Number = when {
        a is Int && b is Int -> a + b
        a is Long && b is Long -> a + b
        a is Float && b is Float -> a + b
        a is Double && b is Double -> a + b
        else -> throw IllegalArgumentException() 

    @Suppress("UNCHECKED_CAST")
    return result as T
}

fun <T: Number> doOperation(a: T, b: T, operationToPerform: (T, T) -> T ) {
    println(operationToPerform(a, b))
}

I have the method doOperations that takes a generics function as a parameter that I intend to run on the other 2 parameters passed. However, invoking the same in main as :

fun main(args: Array<String>) {
    doOperation (2, 3, doSum)
}

is returning errors like:

Error:(15, 24) Kotlin: Function invocation 'doSum(...)' expected
Error:(15, 24) Kotlin: No value passed for parameter 'a'
Error:(15, 24) Kotlin: No value passed for parameter 'b'

Any suggestions on the way to call doOperation with doSum()?

(& changing < T > doSum to < T: Number > doSum throws up one more error: Error:(15, 24) Kotlin: Type parameter bound for T in fun doSum(a: T, b: T): T is not satisfied: inferred type (Int, Int) -> Int is not a subtype of Number)

Upvotes: 1

Views: 153

Answers (1)

MFazio23
MFazio23

Reputation: 1312

For anyone that comes in here at a later date, the fix here was to send in the doSum(...) method like this:

doOperation (2, 3, ::doSum)

Adding the :: before doSum(...) allows you to reference a top-level, local, or member function.

More info: https://kotlinlang.org/docs/reference/lambdas.html#function-types

Upvotes: 1

Related Questions