Home » Android » How to set not null for function params in kotlin

How to set not null for function params in kotlin

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’m creating one function in Kotlin. It validates email and password fields. I want to apply email and password should not be null. @NotNull kinda annotation here.

Does anyone know how to do this in Kotlin? So the caller cannot send the null value.

private fun isEmailAndPasswordValid(email: String, password: String): Boolean {

    if (email.isEmpty()) return false

    if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) return false

    if (password.isEmpty()) return false

    return true
}
Answers:

Kotlin differentiates all types by nullable and not-nullable. For example, the class String can be used for the type String, which is not nullable, and the type String?, which IS nullable, i.e. could hold null.

In your example no nullable types are used, so you’re all good – no additional annotation needed.

The documentation should be studied for further information.

Questions:
Answers:

Kotlin has build-in null safety. String is a non-null type while String? is a nullable type. So, isEmailAndPasswordValid(email: String, password: String) will enforce the value passed to it is non-null.

Questions:
Answers:

The Kotlin language is by default null-safe so when creating a new variable it can’t be null, but when you want a nullable variable you can add The exclamation mark to specify that it can be null for Example String?, Int? …

Not Nullable

var a: String = "bachiri"
a = null // compilation error

Nullable Type

var a: String? = "bachiri"
a = null // OK

and bare in mind if you want to call a function on the nullable Type you should use eighter the check for null variable(1) or use the safe calls(2)

Questions:
Answers:

When I check the Kotlin documentation, I can see that a String variable can’t be set to null, unless you declare it can be, and your compiler will raise an error.

For example, a regular variable of type String can not hold null

https://kotlinlang.org/docs/reference/null-safety.html