MOCKSTACKS
EN
Questions And Answers

More Tutorials








Kotlin Type casting and conversion

Type casting is a process of converting one data type to another type, for example – converting int to long, long to double etc. In this tutorial we will learn how to do type conversion in Kotlin. In Kotlin the conversion is not automatic, we need to explicitly do the type conversion. Type cast objects using the is operator or its negated form !is to perform a runtime check that identifies whether an object conforms to a given type.

fun demo(x: Any) {
    if (x is String) {
        print(x.length) // x is automatically cast to String
    }
}

Kotlin Int to String using toString() function

.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.

fun main() {  
  var x = 10
  var y: String = x.toString()
  println(y)  
}

Output

10

Kotlin Int to Long using toLong() function

We use the toLong() function to convert int to long in Kotlin.
fun main() {  
  val num1: Int = 101
  val num2: Long = num1.toLong()
  println(num2)  
}

Output

101

Conclusion

In this page (written and validated by ) you learned about Kotlin Type casting and conversion . What's Next? If you are interested in completing Kotlin tutorial, your next topic will be learning about: Kotlin String concatenation.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.