kotlin lambda expressions as optional parameter
Asked Answered
A

2

20

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

Arundel answered 4/7, 2017 at 9:2 Comment(4)
What do you want to pass this lambda to?Electromagnet
Side note, there already is a max function available in the JDK, accessible via Math.max(a, b) which does the same thing.Nerland
Regarding your question though, I don't really understand what you're asking - you can pass max as a normal argument to any function call that takes a function of the form (Int, Int) -> Int.Nerland
Here I given MAX as example because i can't share my code , and it should work for all type of lambda expressionsArundel
B
17

You can use your max function as default

fun someDefault(f: (a: Int, b: Int) -> Int = max) {
    f(1, 7)
    // do something
}

or you can also define a method with lambda as parameter which is optional

fun someOptional(f: ((a: Int, b: Int) -> Int)? = null) {
    f?.invoke(1, 7)
}

In both cases (default and optional) you can specify a lambda for the call or you can just omit it

fun call() {
    someDefault()
    someDefault { a, b -> a * b}

    someOptional()
    someOptional { a, b -> a * b}
}
Biceps answered 4/7, 2017 at 9:7 Comment(0)
A
16

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))
}
Anteversion answered 4/7, 2017 at 9:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.