将 Java 转换为包含代码的 Kotlin BiFunction
Convert Java to Kotlin BiFunction containing code
我正在尝试将我的 Java class 转换为 Kotlin。
这是 Java 代码:
Observable.just("Stacey")
.zipWith(Observable.just(6),
(name, age) -> {
String text;
if(age < 18){
text = name + " is a child";
}else{
text = name + "is not a child";
}
return text;
}
);
这就是我将其转换成的:
Observable.just("Stacey")
.zipWith(Observable.just(6),
BiFunction<String, Int, String> {name, age ->
var text: String
if(age < 18){
text = "$name + is a child"
}else{
text = "$name + is not a child"
}
return text
}
)
Lambda 表示法似乎根本不起作用,或者我无法理解。我在 Kotlin 中找到的所有 BiFunctions 示例 return 一个值直接像这样
BiFunction {name, age -> name+age}
这在语法上是正确的,但在我 return 之前我需要一些额外的逻辑。
出现两条错误消息:
'return'这里不允许
类型不匹配。要求:单位,找到:String
但我确实想要 return 一个字符串,而且我还明确声明了它。但是还有什么地方可以放 return?
我也遇到过这个问题,你只需要更换
return 文本与
return@BiFunction 文本
解释可以看这里:
https://tutorialwing.com/labeled-return-or-return-in-kotlin-with-example
我正在尝试将我的 Java class 转换为 Kotlin。 这是 Java 代码:
Observable.just("Stacey")
.zipWith(Observable.just(6),
(name, age) -> {
String text;
if(age < 18){
text = name + " is a child";
}else{
text = name + "is not a child";
}
return text;
}
);
这就是我将其转换成的:
Observable.just("Stacey")
.zipWith(Observable.just(6),
BiFunction<String, Int, String> {name, age ->
var text: String
if(age < 18){
text = "$name + is a child"
}else{
text = "$name + is not a child"
}
return text
}
)
Lambda 表示法似乎根本不起作用,或者我无法理解。我在 Kotlin 中找到的所有 BiFunctions 示例 return 一个值直接像这样
BiFunction {name, age -> name+age}
这在语法上是正确的,但在我 return 之前我需要一些额外的逻辑。 出现两条错误消息:
'return'这里不允许
类型不匹配。要求:单位,找到:String
但我确实想要 return 一个字符串,而且我还明确声明了它。但是还有什么地方可以放 return?
我也遇到过这个问题,你只需要更换 return 文本与 return@BiFunction 文本
解释可以看这里:
https://tutorialwing.com/labeled-return-or-return-in-kotlin-with-example