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

Wat*_* v2 15 kotlin

我有一堆具有可空属性的bean,如下所示:

package myapp.mybeans;

data class Foo(val name : String?);
Run Code Online (Sandbox Code Playgroud)

我在全球空间中有一个方法,如下所示:

package myapp.global;

public fun makeNewBar(name : String) : Bar
{
  ...
}
Run Code Online (Sandbox Code Playgroud)

在其他地方,我需要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);
Run Code Online (Sandbox Code Playgroud)

此外,在这里进行一些转换foo.name,每次用小东西清理它,同时一方面为我提供编译时保证和安全性,这在很大程度上是一个很大的麻烦.是否有一些短手来解决这些情况?

mie*_*sol 18

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

val bar = makeNewBar(foo.name!!)
Run Code Online (Sandbox Code Playgroud)

Null Safety部分所述:

第三种选择是NPE爱好者.我们可以编写b !!,这将返回b的非空值(例如,在我们的示例中为String)或者如果b为null则抛出NPE:

val l = b!!.length 
Run Code Online (Sandbox Code Playgroud)

因此,如果你想要一个NPE,你可以拥有它,但是你必须明确地要求它,并且它不会出现.


Sir*_*lot 6

您可以使用扩展:

fun <T> T?.default(default: T): T {
    return this ?: default
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

fun getNonNullString(): String {
    return getNullableString().default("null")
}
Run Code Online (Sandbox Code Playgroud)