我有一堆豆子具有空的屬性,像這樣:將可空類型轉換爲不可空類型?
package myapp.mybeans;
data class Foo(val name : String?);
而且我有在全球空間的方法,像這樣:
package myapp.global;
public fun makeNewBar(name : String) : Bar
{
...
}
而且別的地方,我需要一個Bar
來自Foo
裏面的東西。所以,我這樣做:
package myapp.someplaceElse;
public fun getFoo() : Foo? { }
...
val foo : Foo? = getFoo();
if (foo == null) { ... return; }
// I know foo isn't null and *I know* that foo.name isn't null
// but I understand that the compiler doesn't.
// How do I convert String? to String here? if I do not want
// to change the definition of the parameters makeNewBar takes?
val bar : Bar = makeNewBar(foo.name);
而且,這裏與foo.name
做一些轉換爲每次每一件小事潔淨了,而在一方面爲我提供的編譯時間保證和安全性這是一個大麻煩最的時間。是否有一些空手來解決這些情況?
我相信編譯器只會證明'foo!='null如果它在條件塊內。你可以嘗試用'if(foo!= null){...}'替換你的空檢查。 – Actorclavilis
[在Kotlin中,處理可空值的慣用方法是什麼,引用或轉換它們是什麼](http:/ /stackoverflow.com/questions/34498562/in-kotlin-what-is-the-idiomatic-way-to-deal-with-nullable-values-referencing-o) –