gpt4 book ai didi

kotlin - "Pattern match"不适用于 Int 子句(分支)

转载 作者:行者123 更新时间:2023-12-01 09:50:57 28 4
gpt4 key购买 nike

我在 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 当前的情况。

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

enter image description here

最佳答案

当您传递参数时,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

关于kotlin - "Pattern match"不适用于 Int 子句(分支),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37755789/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com