1

I want to get View's text. So I check that view was TextView, and used v.text. In this situation, v.text is Charsequence!. and I try to change v.text to String. I got two situation, v.text.toString and v.text as String. What are they difference?

override fun onClick(v: View?) {
        when(v) {
            is TextView -> {
                Log.d("v.text", v.text)
                // v.text is Charsequence but msg need String
            }
        }
    }
KRMKGOLD
  • 25
  • 1
  • 5

2 Answers2

7

v.text as String means "force-cast v.text to a String". This will crash your app if v.text happens to be some other kind of CharSequence than String, e.g. SpannedString. Even though it will work in many cases since v.text often is a String, it is not what you should use.

v.text.toString() means "call the toString method on the v.text object". This will return a String representation of the object, and is what you should use in this case.

Here is some sample code to demonstrate the difference:

v?.text = SpannedString("spanned string")

// Will print "v.text  : spanned string" to logcat
Log.d("v.text", v?.text.toString())

// Will crash with java.lang.ClassCastException: android.text.SpannedString cannot be cast to java.lang.String
Log.d("v.text", v?.text as String) 
Enselic
  • 4,434
  • 2
  • 30
  • 42
2

toString() is conversation from Some type to String type.

as String is unsafe casting that might cause ClassCastException.

Antonis Radz
  • 3,036
  • 1
  • 16
  • 34