Kotlin 等价于联合类型上的一些 F# 代码匹配
Kotlin equivalent of some F# code matching on union type
我正在学习 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)
// 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)
文档
我正在学习 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)
// 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)
文档