首页 文章

将可空类型转换为非可空类型?

提问于
浏览
7

我有一堆具有可空属性的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 回答

  • 12

    你需要这样的双重感叹号:

    val bar = makeNewBar(foo.name!!)
    

    Null Safety section中所述:

    第三种选择是NPE爱好者 . 我们可以编写b !!,这将返回b的非空值(例如,在我们的示例中为String)或者如果b为null则抛出NPE:val l = b !! . length
    因此,如果你想要一个NPE,你可以拥有它,但你必须明确地要求它,并且它不会出现 .

相关问题