使用when
来通过智能转换替换OR
。
在网上看到一个问题是说有两个方法,同名不同参数1
2
3
4
5
6fun foo(long: Long) {
// doSomething
}
fun foo(int: Int) {
// doSomething
}
然后现在有个变量是未定类型val someValue: Any = "0" // 0 or 0L
,在使用foo
方法的时候,然后他是这样写的,问说如何智能转换,不要使用||
。
1 | if (someValue is Int || someValue is Long) { |
使用when
来替代它1
2
3
4when (someValue) {
is Long -> foo(someValue)
is Int -> foo(someValue)
}
这样就体现了Kotlin的智能转换功能了