Kotlin学习_when的一个小功能

使用when来通过智能转换替换OR

在网上看到一个问题是说有两个方法,同名不同参数

1
2
3
4
5
6
fun foo(long: Long) {
// doSomething
}
fun foo(int: Int) {
// doSomething
}

然后现在有个变量是未定类型val someValue: Any = "0" // 0 or 0L,在使用foo方法的时候,然后他是这样写的,问说如何智能转换,不要使用||

1
2
3
4
5
6
7
8
if (someValue is Int || someValue is Long) {
foo(someValue)
}
// 或者这样
if (someValue is Int)
foo(someValue)
else if (someValue is Long)
foo(someValue)

使用when来替代它

1
2
3
4
when (someValue) {
is Long -> foo(someValue)
is Int -> foo(someValue)
}

这样就体现了Kotlin的智能转换功能了