如何使用Kotlin在这个函数中实现not null return?
How to achieve a not null return in this function by using Kotlin?
lateinit var x:String
private fun defineTheIDofTheRoom ():String {
while (x != "") {
x = intent.getStringExtra("ID1")!!
x = intent.getStringExtra("ID2")!!
x = intent.getStringExtra("ID3")!!
x = intent.getStringExtra("ID4")!!
}
return x
}
//我希望这个函数给我一个不为空的结果(字符串),我将在其他地方使用它。其中 3 个将给出空结果,只有其中一个不为空。 . 如果有人能提供帮助,我将很高兴从现在开始非常感谢...
您可以像这样将 return x
放在 while
块之外
private fun defineTheIDofTheRoom (): String {
while (x != "") {
x = intent.getStringExtra("ID1")!!
x = intent.getStringExtra("ID2")!!
x = intent.getStringExtra("ID3")!!
x = intent.getStringExtra("ID4")!!
}
return x
}
3 of them will give null as a result, only one of them will be not null...
the thing is here, code doesnt even go after the first try through others..so ı guess the problem is why in my while block it executes the first line but not the others, maybe ı have a mistake in while block?
如果前 3 个实际上不是 null,它们将赋值给 x
,但该值将立即被覆盖; 仅
的效果
x = intent.getStringExtra("ID1")!!
x = intent.getStringExtra("ID2")!!
x = intent.getStringExtra("ID3")!!
行是如果其中任何一个是null
就抛出异常。我怀疑你想要
x = (intent.getStringExtra("ID1") ?: intent.getStringExtra("ID2") ?: intent.getStringExtra("ID3") ?: intent.getStringExtra("ID4"))!!
并且没有 while
循环。如果所有 4 个都是 null
并且 ?: "some default case"
否则你特别想崩溃,我只会使用最后一个 !!
。
lateinit var x:String
private fun defineTheIDofTheRoom ():String {
while (x != "") {
x = intent.getStringExtra("ID1")!!
x = intent.getStringExtra("ID2")!!
x = intent.getStringExtra("ID3")!!
x = intent.getStringExtra("ID4")!!
}
return x
}
//我希望这个函数给我一个不为空的结果(字符串),我将在其他地方使用它。其中 3 个将给出空结果,只有其中一个不为空。 . 如果有人能提供帮助,我将很高兴从现在开始非常感谢...
您可以像这样将 return x
放在 while
块之外
private fun defineTheIDofTheRoom (): String {
while (x != "") {
x = intent.getStringExtra("ID1")!!
x = intent.getStringExtra("ID2")!!
x = intent.getStringExtra("ID3")!!
x = intent.getStringExtra("ID4")!!
}
return x
}
3 of them will give null as a result, only one of them will be not null...
the thing is here, code doesnt even go after the first try through others..so ı guess the problem is why in my while block it executes the first line but not the others, maybe ı have a mistake in while block?
如果前 3 个实际上不是 null,它们将赋值给 x
,但该值将立即被覆盖; 仅
x = intent.getStringExtra("ID1")!!
x = intent.getStringExtra("ID2")!!
x = intent.getStringExtra("ID3")!!
行是如果其中任何一个是null
就抛出异常。我怀疑你想要
x = (intent.getStringExtra("ID1") ?: intent.getStringExtra("ID2") ?: intent.getStringExtra("ID3") ?: intent.getStringExtra("ID4"))!!
并且没有 while
循环。如果所有 4 个都是 null
并且 ?: "some default case"
否则你特别想崩溃,我只会使用最后一个 !!
。