4

我正在学习 Kotlin,想知道是否有人可以就以下 F# 片段在惯用的 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"

太感谢了。(顺便说一句,该片段来自 Scott Wlaschin 精彩的Domain Modeling Made Functional

4

1 回答 1

5
// 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")
  } 
}

您可以像传递任何其他变量一样传递此函数类型并调用它:

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

文档

于 2020-12-28T21:59:26.733 回答