Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

Kotlin - Operator '==' cannot be applied to 'Editable!' and 'String' when comparing string

So, Just started working with Kotlin in Android Studio 3.0 Canary 7 and I was carrying out a simple operation of checking if string is empty or not.

Here's my simple layout:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click me"
        android:id="@+id/btnClick"/>
<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Write something to print"
        android:id="@+id/edtTxt"/>

and with MainActivity.kt I've below stuff

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btnClick.setOnClickListener {
            val message=edtTxt.text
            if (message == "")
                longToast("Come on! Write something")
            else
                longToast("You've written $message")
        }
    }
}

So initially I've written code within clicklistener as

val message=edtTxt.text
if (message.equals("")) //this here
    longToast("Come on! Write something")
else
    longToast("You've written $message")

Later on the IDE suggested to replace it with

IDE Suggestion

and I tried on doing that with if (message=="") but that started showing Operator '==' cannot be applied to 'Editable!' and 'String' when comparing string error. This is totally confusing.

My doubts here:

Upvotes: 6

Views: 4910

Answers (2)

Vasileios Pallas
Vasileios Pallas

Reputation: 4877

edtTxt.text is just a replacement for java's editTxt.getText(). So basically this has to be converted to String before using == operator.

If you want to get the String from the Editable object use toString() method.

val message=edtTxt.text.toString()

Upvotes: 8

Ahmad Aghazadeh
Ahmad Aghazadeh

Reputation: 17131

btnClick.setOnClickListener {
    // edtTxt.text  type of EditText
    val message=edtTxt.text.toString() 
    if (message == "")
        longToast("Come on! Write something")
    else
        longToast("You've written $message")
}

Upvotes: 2

Related Questions