Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set not null for function params in kotlin

Tags:

android

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
}
like image 343
N Sharma Avatar asked Dec 04 '25 18:12

N Sharma


2 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.

like image 67
s1m0nw1 Avatar answered Dec 06 '25 08:12

s1m0nw1


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)

like image 36
Bachiri Taoufiq Abderrahman Avatar answered Dec 06 '25 09:12

Bachiri Taoufiq Abderrahman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!