我想使用Kotlin中的when()表达式从函数返回不同的值。输入是一个String,但是它可能被解析为一个Int,所以如果可能的话,我想返回解析的Int,如果不是的话,返回一个String。因为输入是一个String,所以我不能使用is类型check表达式。
有什么惯用的方法来达到这个目的吗?
我的问题是when()表达式应该是什么样子,而不是返回类型。
发布于 2021-03-08 13:50:10
如果要检查字符串是否为数字(Int),并执行一些简单的解决方案,可以如下所示:
if (myString.toIntOrNull() != null) {
//Write your code you want to execute if myString is (Int)
} else {
//Write your code you want to execute if myString is (not Int)
}https://stackoverflow.com/questions/48116753
复制相似问题