处理“不可能进行智能转换"的这种情况的最佳方式是在服务器上进行处理. [英] Best way to handle such scenario where "smart cast is imposible"
本文介绍了处理“不可能进行智能转换"的这种情况的最佳方式是在服务器上进行处理.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道处理这种情况的最佳方法是什么
I wonder what is the best way to handle such scenario
class Person(var name:String? = null, var age:Int? = null){
fun test(){
if(name != null && age != null)
doSth(name, age) //smart cast imposible
}
fun doSth (someValue:String, someValue2:Int){
}
}
调用doSth方法并确保名称和年龄不为null的最简单方法是什么?
What is the simplest way to call doSth method and making sure that name and age are nt null?
我正在寻找一种简单的方法,例如在一个可变方案中,我会简单地使用let
I am looking for something simple as with one variable scenario where I would simply use let
name?.let{ doSth(it) }
推荐答案
您可以根据需要随意嵌套let
:
You can nest let
as much as you like so:
fun test(){
name?.let { name ->
age?.let { age ->
doSth(name, age) //smart cast imposible
}
}
}
另一种可能更容易遵循的方法是使用局部变量:
Another approach, that might be easier to follow, is to use local variables:
fun test(){
val name = name
val age = age
if(name != null && age != null){
doSth(name, age)
}
}
最后但并非最不重要的一点,请考虑将Person
更改为不变,如下所示:
Last but not least, consider changing Person
to be immutable like so:
data class Person(val name:String? = null, val age:Int? = null){
fun test(){
if(name != null && age != null){
doSth(name, age)
}
}
...
}
这篇关于处理“不可能进行智能转换"的这种情况的最佳方式是在服务器上进行处理.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文