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

f#

我正在学习 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 精彩的领域建模使功能)

回答

// 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)

文档

  • 高阶函数和 Lambda
  • 科特林 | 函数类型、Lambda 和高阶函数

以上是Kotlin等效于联合类型上的某些F#代码匹配的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>