N Sharma
N Sharma

Reputation: 34497

How to set not null for function params in kotlin

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
}

Upvotes: 2

Views: 5607

Answers (4)

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)

Upvotes: 3

s1m0nw1
s1m0nw1

Reputation: 81879

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.

Upvotes: 5

CrazyApple
CrazyApple

Reputation: 482

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.

Upvotes: 2

gi097
gi097

Reputation: 7703

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

Upvotes: 1

Related Questions