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

x80*_*486 3 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())})")
}
Run Code Online (Sandbox Code Playgroud)

...所以我期待那typeCheck(5)回归,(small) integer而不是integer像目前那样.

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

在此输入图像描述

Rus*_*lan 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"
}
Run Code Online (Sandbox Code Playgroud)

要么

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

表情时

  • 它不起作用,因为`when(foo){}`和`when {}`具有不同的语义.这种语义在文档中很好地描述了. (2认同)