Search code examples
kotlinf#arrow-kt

Kotlin equivalent of some F# code matching on union type


I'm learning Kotlin and am wondering if anyone out there could advise on what the following snippet of F# might look like in idiomatic Kotlin.

// a function that has an Option<int> as input
let printOption x = match x with
| Some i -> printfn "The int is %i" i
| None -> printfn "No value"

Thanks a million. (btw, the snippet is from Scott Wlaschin's wonderful Domain Modeling Made Functional)


Solution

  • // as a function
    fun printOption(x: Int?) {
      when(x) {
        null -> print("No Value")
        42 -> print("Value is 42")
        else -> print("Value is $x")
      } 
    }
    
    // as a functional type stored in printOption
    val printOption: (Int?) -> Unit = { x ->
      when(x) {
        null -> print("No Value")
        42 -> print("Value is 42")
        else -> print("Value is $x")
      } 
    }
    

    You can pass this function type like any other variable and call it like:

    printOption(42)
    // or
    printOption.invoke(42)
    

    Documentation