“模式匹配”对Int子句(分支)不起作用

时间:2016-06-10 19:24:37

标签: kotlin

我在Kotlin(我开始学习)中有这段代码:

package io.shido.learning

import java.time.Instant

fun typeCheck(any: Any): Any = when (any) {
  (any is Int && any < 10) -> "(small) integer"
  is Int -> "integer"
  is Double -> "double"
  is String -> "string"
  else -> "another Any"
}

fun main(args: Array<String>) {
  println("type check for: 5 (${typeCheck(5)})")
  println("type check for: 20 (${typeCheck(20)})")
  println("type check for: 56.0 (${typeCheck(56.0)})")
  println("type check for: \"a string\" (${typeCheck("a string")})")
  println("type check for: Instant (${typeCheck(Instant.now())})")
}

...所以我希望typeCheck(5)返回(small) integer而不是integer

有没有人有任何见解?第一个分支true确实是5

enter image description here

1 个答案:

答案 0 :(得分:7)

传递参数时,when检查参数是否与分支中的值匹配,而5与第一个分支中的计算true不匹配。所以基本上你可以这样修复你的代码:

fun typeCheck(any: Any): Any = when {
    (any is Int && any < 10) -> "(small) integer"
    any is Int -> "integer"
    any is Double -> "double"
    any is String -> "string"
    else -> "another Any"
}

fun typeCheck(any: Any): Any = when (any) {
    in 0..10 -> "(small) integer"
    is Int -> "integer"
    is Double -> "double"
    is String -> "string"
    else -> "another Any"
}

请参阅When Expression