【问题标题】:Kotlin: How to use if statements in a lambda expressionKotlin:如何在 lambda 表达式中使用 if 语句
【发布时间】:2023-01-25 21:01:02
【问题描述】:

我确实试过了,但我遇到了错误。

fun main() {
    val addExclamationMark: (String) -> String = {if it.contains("!") -> it else -> it + "!"}
    println(addExclamationMark("Hallo Welt"))
}

类型不匹配:推断类型为 Unit 但应为 String 期待括号 '(...)' 中的条件 意外标记(使用“;”分隔同一行的表达式)

您能否通过一些解释告诉我如何正确执行此操作,以便我更了解 Kotlin? ;)

【问题讨论】:

  • 如果流量控制是有效语法,您从哪里得到使用箭头的?这是一些新的实验性功能吗?

标签: android firebase android-studio kotlin android-jetpack-compose


【解决方案1】:

错误Type mismatch: inferred type is Unit but String was expected是因为你将返回数据类型定义为String,但你没有返回任何东西。有两个原因:

  • -> 不是必需的,它们太多了
  • 条件必须在括号中

放在一起,这有效:

fun main() {
    val addExclamationMark: (String) -> String = { if (it.contains("!")) it else it + "!"}
    println(addExclamationMark("Hallo Welt"))
}

Check here

【讨论】:

    【解决方案2】:

    你必须传递一个字符串,没有返回任何东西,

    Val addExclamationMark: (String) -> String = {
                if (it.contains("!")) {
                    it
                } else {
                    "$it!"
                }
            }
    
        println(addExclamationMark("Hallo Welt"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      相关资源
      最近更新 更多