Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • What does this actually mean?
  • How can I apply what IDE suggested or is there any workaround to get this done?
like image 462
Guruprasad J Rao Avatar asked Jul 19 '17 10:07

Guruprasad J Rao


2 Answers

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()
like image 151
Vasileios Pallas Avatar answered Sep 21 '22 12:09

Vasileios Pallas


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")
}
like image 41
Ahmad Aghazadeh Avatar answered Sep 21 '22 12:09

Ahmad Aghazadeh