Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why strip() is deprecated in Kotlin and what should I use instead?

Tags:

kotlin

For String.strip() I get warning 'strip(): String!' is deprecated. This member is not fully supported by Kotlin compiler, so it may be absent or have different signature in next major version"

Why is it? "strip" comes from Java String What should I use?

like image 830
Pavel Bernshtam Avatar asked Sep 13 '25 19:09

Pavel Bernshtam


1 Answers

Use trim() instead. It does the same thing.

String.strip() is a new function in Java 11. Kotlin targets JVM 6 by default, so I was unable to reproduce your issue at first, I got a compilation error. Using JVM 11 as target in Android Studio worked with your compiler warning.

Kotlin's string class (kotlin.String) is not the same as Java's string class (java.lang.String). The Kotlin type is however mapped to the Java type (quote):

Kotlin types such as List, MutableList, String, CharSequence etc. are all compiled to their java equivalents, and thus any runtime checks will not be able to distinguish between them. At compile-time, however, they are distinct types with different sets of members. In particular, the Kotlin types do not have all members that the corresponding Java types have. They have those listed in the Kotlin std lib reference, as well as a few extra JVM specific ones (such as Collection.stream())

kotlin.String does not have a .strip() function. You are just "incidentally" calling java.lang.String.strip() which happens to be there in some target JVMs but not defined in Kotlin. If you look at the kotlin.String source in your IDE you can see it is not defined there.

The reason it is not there is because it was explicitly graylisted by the Kotlin team:

Some methods in JDK classes are undesirable in Kotlin built-ins (e.g. a lot of String methods or List.sort(), because there are Kotlin analogues with better signatures already defined).


  • Extended Reading

  • Extended Reading 2

  • The commit which put .strip() on the graylist

like image 160
xjcl Avatar answered Sep 15 '25 10:09

xjcl