AVEbrahimi
AVEbrahimi

Reputation: 19164

Kotlin function that receives two numbers and returns sum and multiply of them

I am newbie in Kotlin lambda expressions, I try to build a function to have two arguments and returns a function with to parameters:

val sumAndMultiply:(Int,Int) -> (Int,Int) -> Unit = { a,b -> (a+b,a*b)}

But it's not compiling. Generally how can I return a headless function in Kotlin?

Upvotes: 1

Views: 2549

Answers (3)

Marko Topolnik
Marko Topolnik

Reputation: 200168

please help me creating a function that has two arguments and returns a function with two arguments.

This is a function that takes two arguments and returns a function with two arguments.

fun binaryFunReturningBinaryFun(a: Int, b: Int): (Int, Int) -> Int =
        { x, y -> (a + x) * (b + y) }

Upvotes: 4

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22605

Kotlin has no support for tuples. You would have to use Pair:

val sumAndMultiply: ((Int,Int) -> Pair<Int,Int>) = { a,b -> Pair(a+b,a*b) }

Another solution would be to create data class, for example:

data class SumAndMultiplication(val sum: Int, val multiplication: Int)
val sumAndMultiply2: ((Int,Int) -> SumAndMultiplication) = { a,b -> SumAndMultiplication(a+b,a*b) }

Upvotes: 3

Jaydip Kalkani
Jaydip Kalkani

Reputation: 2607

I have done same thing using below code and it worked.

var rtn:(Int,Int) -> Unit = {x,y -> println("${x} ${y}")}
val sumAndMultiply: (Int,Int) -> Any = { a,b -> rtn(a+b,a*b)}
sumAndMultiply(1,3)

Explanation

You want to return a function from your lambda function so, first of all you have to create the function which you want to return. So, i have created rtn function for this. I have created rtn also as a lambda function. You can create as you want.

Then i have changed return type of sumAndMultiply lambda function and returned function rtn which we have created.

Upvotes: 2

Related Questions