Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin lambda expressions as optional parameter

How can I pass lambda expression as optional parameter in Kotlin language

val max = { a: Int, b: Int ->
  if (a > b)
      a
  else
      b
}

I have to pass above thing is like optional parameter

like image 843
Prathap Avatar asked Jul 04 '17 09:07

Prathap


People also ask

Does Kotlin support lambda expressions?

You use lambda expressions extensively in Android development and more generally in Kotlin programming.

When a lambda function has only one parameter what is its default name in Kotlin?

Only one parameter can be marked as vararg . If a vararg parameter is not the last one in the list, values for the subsequent parameters can be passed using named argument syntax, or, if the parameter has a function type, by passing a lambda outside the parentheses.

What is the benefit of lambda expressions in Kotlin?

A lambda expression is a shorter way of describing a function. It doesn't need a name or a return statement. You can store lambda expressions in a variable and execute them as regular functions. They can also be passed as parameters to other functions or be the return value.


1 Answers

The following defines a function that accepts a function, and specifies a default value for the passed function if none is supplied.

fun foobar(fn: (a: Int, b: Int) -> Int = { a: Int, b: Int -> if (a > b) a else b }) {
  println(fn(42, 99))
}

You can pass your own functions:

val min = { a: Int, b: Int -> if (a <= b) a else b }
foobar(min)

val max = { a: Int, b: Int -> if (a > b) a else b }
foobar(max)

You can omit the function and use the default:

foobar()

Alternatively you could refer to the standard library maxOf function as the default, rather than write your own:

fun foobar(fn: (a: Int, b: Int) -> Int = ::maxOf) {
  println(fn(42, 99))
}
like image 138
Greg Kopff Avatar answered Oct 14 '22 23:10

Greg Kopff