Kotlin 等效于联合类型上的某些 F# 代码匹配

ct_*_*ct_ 4 f# kotlin arrow-kt

我正在学习 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"
Run Code Online (Sandbox Code Playgroud)

太感谢了。(顺便说一句,该片段来自 Scott Wlaschin 精彩的领域建模使功能

Chr*_*anB 5

// as a function
fun printOption(x: Int?) {
  when(x) {
    null -> print("No Value")
    42 -> print("Value is 42")
    else -> print("Value is $x")
  } 
}
Run Code Online (Sandbox Code Playgroud)
// 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")
  } 
}
Run Code Online (Sandbox Code Playgroud)

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

printOption(42)
// or
printOption.invoke(42)
Run Code Online (Sandbox Code Playgroud)

文档