簡體   English   中英

如何使用 Kotlin 在此 function 中實現非 null 返回?

[英]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
     }

//ı want this function give me a result which is not null (String) and ı will use it somewhere else.3 of them will give null as a result, only one of them will be not null... if somebody can help我會很高興從現在開始非常感謝...

您可以像這樣將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 個會給出 null,只有一個不會是 null...

事情就在這里,在第一次嘗試通過其他代碼之后,代碼甚至沒有 go ..所以我猜問題是為什么在我的 while 塊中它執行第一行而不是其他行,也許我在 while 塊中有錯誤?

如果前 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"否則。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM