将可为空的类型转换为其不可为空的类型? [英] Convert a nullable type to its non-nullable type?

查看:78
本文介绍了将可为空的类型转换为其不可为空的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a bunch of beans that have nullable properties like so:

package myapp.mybeans;

data class Foo(val name : String?);

我在全局空间中有一个像这样的方法:

And I have a method in the global space like so:

package myapp.global;

public fun makeNewBar(name : String) : Bar
{
  ...
}

在其他地方,我需要使用Foo内部的内容制作一个Bar.所以,我这样做:

And somewhere else, I need to make a Bar from the stuff that's inside Foo. So, I do this:

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进行一些转换以每次用小东西清理它,而一方面为我提供了编译时保证和安全性,但在大多数情况下这是一个很大的麻烦.有一些解决这些情况的捷径吗?

Also, doing some conversion here with foo.name to cleanse it every time with every little thing, while on the one hand provides me compile-time guarantees and safety it is a big bother most of the time. Is there some short-hand to get around these scenarios?

推荐答案

您需要像这样的双感叹号:

You need double exclamation mark like so:

val bar = makeNewBar(foo.name!!)

无效安全"部分中所述:

As documented in Null Safety section:

第三个选项适用于NPE爱好者.我们可以写b !! 返回b的非空值(例如,在我们的示例中为String)或抛出 如果b为null,则为NPE:

The third option is for NPE-lovers. We can write b!!, and this will return a non-null value of b (e.g., a String in our example) or throw an NPE if b is null:

val l = b!!.length 

因此,如果您想要NPE,可以拥有它,但是必须明确要求它,并且它不会出现在NPE之外. 蓝色.

Thus, if you want an NPE, you can have it, but you have to ask for it explicitly, and it does not appear out of the blue.

这篇关于将可为空的类型转换为其不可为空的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆