我有一堆豆子具有空的属性,像这样:将可空类型转换为不可空类型?
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) –