ste9206 ste9206 -4 years ago 146
Android Question

kotlin verify input fields

I'm moving from Java to Kotlin for my Android development. I want to check if a field in EditText is empty or not. So I've tried to make this:

override fun checkFields() {

val username = username.text.toString().trim().takeUnless { username.text.isNullOrEmpty() } ?: presenter.usernameError()
val password = password.text.toString().trim().takeUnless { password.text.isNullOrEmpty() } ?: presenter.passwordError()

presenter.signInWithUsernameAndPassword(username as String,password as String)

but there are two problems:

  1. it passes also to the
    also if username/password is empty

  2. it crashes because gives me this error:

    java.lang.ClassCastException: kotlin.Unit cannot be cast to java.lang.String

converts String to Unit?


Answer Source

The first statement in the method is like the following in Java.

String username = !username.text.isNullOrEmpty() ? username.text.toString().trim() : presenter.usernameError();

This is why you get the ClassCastException if presenter.usernameError() is a Unit-typed (or void in Java) function. I think this is not what you want.

Provided that both presenter.usernameError() and presenter.passwordError() is a Unit-typed functions, you can

val username = username.text.toString().trim().takeUnless { it.isNullOrEmpty() } ?: return presenter.usernameError()
val password = password.text.toString().trim().takeUnless { it.isNullOrEmpty() } ?: return presenter.usernameError()

presenter.signInWithUsernameAndPassword(username as String,password as String)

it refers to username.text.toString().trim() or password.text.toString().trim(), which are the instances that called takeUnless method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download