1

I do not know what's use of nullable in some case in Kotlin. Let me hold an example.

There is a method.

fun hello(name: String)

As you see, the param name is non null. Then I will use it.

hello(bob!!) // bob is a nullable string

If bob is null, above code will throw KotlinNullPointerException. So I have to wrap check.

if(bob != null) {
    hello(bob!!)
}

So in this situation, what's the best practice? And what's use of nullable?

CoXier
  • 2,523
  • 8
  • 33
  • 60

3 Answers3

1

It is a matter of you code business logic to decide.

Usually you will want to use the '!!' operator in case you are 100% sure that bob is not null. In that case '!!' is a clean non-verbose way to ignore the option that 'bob' is null.

If there is a chance that bob is null, use if/else or in case that it is a business error it is advisable to throw an appropriate business exception or handle it in the usual way you are handling errors in your project.

Oz Molaim
  • 2,016
  • 4
  • 20
  • 29
-1

This is how you would use such a function:

fun hello(bob: String) {
    println(bob);
}
hello("Bob!!");

What this means is that the function hello has a parameter named bob, with a datatype of String.

In your example, you are giving the hello function a variable that has not been declared (bob), and as such the JVM cannot pass along anything but null. If you want to pass in a variable named bobby, the code would look like this:

fun hello(bob: String) {
    println(bob);
}
val bobby = "Hello!!!";
hello(bobby);

Hope this helps in your endeavors :)

-1

What's use of nullable?

Take for example a boolean variable which can only hold 2 types of values, true of false. There is no way to signify "undefined". Sometimes we need a way to tell that variable is in an undefined state. For eg, in database or network interaction, you may not receive any value so then variable has to exist in some undefined state and that's what null value signifies. This not just applies to Kotlin, it applies to any language.

what's the best practice?

With nullable types, there is always a risk of null pointer exception, so better check for null before accessing it, and in here

if(bob != null) {
    hello(bob!!)
}

no need to do bob!!, just bob will do, since you have done a null check, Compiler keeps track of the null check and will let you use that variable.

Use non-null assertion (!!) when you are absolutely sure the variable is not null and in that case, no need to surround with null check as well.

Binary Baba
  • 1,953
  • 2
  • 16
  • 23