Ethan
Ethan

Reputation: 82

Kotlin string exists but can't use almost all string functionality

Summary: I have a string from which I can print and use substring, but can't use attributes such as length or functions such as .toInt() or .compareTo(), why would this be the case?

var s = "20"
val myToast = Toast.makeText(this, s, Toast.LENGTH_SHORT)
myToast.show()
//20

val myToast2 = Toast.makeText(this, s.length, Toast.LENGTH_SHORT)
myToast2.show()
//The app crashes with the error: android.content.res.Resources$NotFoundException: String resource ID #0x2

I can call substring on string s, but I can't call length, toInt(), compareTo(), etc.

The string clearly exists since I can print it and use substring but if that is true why does my app throw an error when I try to use other attributes and functions from it?

Upvotes: 1

Views: 92

Answers (2)

Ben P.
Ben P.

Reputation: 54264

There are two overloads of Toast.makeText(). One accepts a String as the second argument, and displays that string. The other accepts an Int as the second argument, and displays whatever string resource has that integer id. (Normally you'd pass something like R.string.my_string here.)

When you call .length on your String, you'll get an Int back. And that means you wind up calling the second overload, which then looks for a string resource with the id 2. That doesn't exist, so you crash.

If you want to just display the number 2, then you need to make this a String again. You can use .toString() or "${s.length}", and so on.

Upvotes: 2

aspmm
aspmm

Reputation: 84

Add .toString at the end of length,toInt(),compareTo(), etc. because s.length return int :not String

Here is your modified answer var s = "20" val myToast = Toast.makeText(this, s, Toast.LENGTH_SHORT) myToast.show() //20

val myToast2 = Toast.makeText(this, s.length.toString(), Toast.LENGTH_SHORT) myToast2.show()

Upvotes: 0

Related Questions