What is the equivalent of String.valueOf() in Kotlin? I want to convert the java code in kotlin code.
var count = 0
for(i in 0 until rings.length){
if(rings.contains("R" String.valueOf(i)) && rings.contains("G" String.valueOf(i)) && rings.contains("B" String.valueOf(i)))
count
}
return count
I checked kotlin documentation, but I don't undertand too much. It's kind of confusing.
CodePudding user response:
How about using Kotlin's string templates "$i"
"R" String.valueOf(i)
becomes:
"R$i"
CodePudding user response:
String.valueOf(X) converts X object to a string by the call of X.toString() or returns "null" if X is null.
Your code tries to convert i to string and i can't be null, so you can replace it to .toString()
rings.contains("R" i.toString()) && rings.contains("G" i.toString()) && rings.contains("B" i.toString())
Kotlin allows you to concat string with object of any type or null, so the expression can be simplified:
rings.contains("R" i) && rings.contains("G" i) && rings.contains("B" i)
And the other variant is the string interpolation:
rings.contains("R$i") && rings.contains("G$i") && rings.contains("B$i")