【问题标题】:Calling String method in Kotlin when block阻塞时在Kotlin中调用String方法
【发布时间】:2020-01-25 07:35:13
【问题描述】:

目前我有一个像这样的 when 块:

val foo = getStringFromBar()

when {
    foo == "SOMETHING" -> { /*do stuff*/ }
    foo == "SOMETHING ELSE" -> { /*do other stuff*/ }
    foo.contains("SUBSTRING") -> { /*do other other stuff*/ }
    else -> { /*do last resort stuff*/ }
}

有没有办法把它简化成这样:

val foo = getStringFromBar()

when (foo) {
    "SOMETHING" -> { /*do stuff*/ }
    "SOMETHING ELSE" -> { /*do other stuff*/ }
    .contains("SUBSTRING") -> { /*do other other stuff*/ }  // This does not work
    else -> { /*do last resort stuff*/ }
}

【问题讨论】:

    标签: android kotlin syntax kotlin-when


    【解决方案1】:

    你可以使用with

    试试这个方法

        with(foo) {
            when {
                equals("SOMETHING") -> println("Case 1")
                equals("something",false) -> println("Case 2")
                contains("SUBSTRING") -> println("Case 3")
                contains("bar") -> println("Case 4")
                startsWith("foo") -> println("Case 5")
                else -> println("else Case")
            }
        } 
    

    【讨论】:

      【解决方案2】:

      试试这个:-

       with(foo) {
          when {
              equals("SOMETHING") -> { //do stuff}
              equals("something",false) -> { //do stuff}
              contains("SUBSTRING") -> { //do stuff}
              contains("bar") -> { //do stuff}
              startsWith("foo") -> { //do stuff}
              else -> { //do stuff}
          }
      } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-10
        • 1970-01-01
        • 2020-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多