Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a nullable type to its non-nullable type?

Tags:

kotlin

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 {   ... } 

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); 

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?

like image 258
Water Cooler v2 Avatar asked Sep 06 '16 13:09

Water Cooler v2


People also ask

What is the difference between nullable and non-nullable?

Nullable variables may either contain a valid value or they may not — in the latter case they are considered to be nil . Non-nullable variables must always contain a value and cannot be nil . In Oxygene (as in C# and Java), the default nullability of a variable is determined by its type.

What is non-nullable type in C#?

You specify that if the parameter is not null, the method does not return null.

How do you make a nullable type in C#?

You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.


1 Answers

You need double exclamation mark like so:

val bar = makeNewBar(foo.name!!) 

As documented in Null Safety section:

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  

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.

like image 178
miensol Avatar answered Oct 07 '22 20:10

miensol