我有一堆具有可空属性的bean,如下所示:
package myapp.mybeans;
data class Foo(val name : String?);
我在全球空间中有一个方法,如下所示:
package myapp.global;
public fun makeNewBar(name : String) : Bar
{
...
}
在其他地方,我需要从 Foo
中的内容中创建一个 Bar
. 所以,我这样做:
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
进行一些转换,每次都用它来清理它,同时一方面为我提供编译时保证和安全性,这在很大程度上是一个很大的麻烦 . 是否有一些短手来解决这些情况?
1 回答
你需要这样的双重感叹号:
如Null Safety section中所述: