Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

android - Kotlin: why would you want to convert Int.toString?

i'm still new to kotlin so take my question with a grain of salt

so i've been learning about kotlin and in one of the articles i was reading about had this code as an example of how to use .toString

val sum1 = { a: Int, b: Int -> 
    val num = a + b 
    num.toString()   //convert Integer to String 
} 
fun main(args: Array<String>) { 
    val result1 = sum1(2,3) 
    println("The sum of two numbers is: $result1") 
} 

Output:

The sum of two numbers is: 5

as i understand it, it's a "5" but of type string.. but why??

we can just simplify the code and get the same outcome:

    val sum1 = { a: Int, b: Int -> a + b }

    val result1 = sum1(2,3)
    println("The sum of two numbers is: $result1")

output:

The sum of two numbers is: 5

so.. i've seen examples of how to use it, but i still didn't find anything to explain why you'd want to use it

question from:https://stackoverflow.com/questions/65661398/kotlin-why-would-you-want-to-convert-int-tostring

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

.toString() returns a string representation of the object. It is not just restricted to converting Int to String. You can use it to convert other data type like Boolean to String.

So whenever a a developer need to store Int as a String, he/she can cast Int to String with the help of .toString().

The above code snippet shared by you is way generic, hence you got confused.

To summarize, whenever you want to store/map any data-type into String, then use .toString().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...