Ilham Bagus Bahrudin
Ilham Bagus Bahrudin

Reputation: 79

as Int vs toInt(), what's the difference between the two?

I have the question


fun main(args : Array<String>){
    val aa = "1"
    val bb = aa.toInt()  // <----- no problem
    println(bb)

    var cc = "1"
    var dd = cc as Int   // <----- exception
    println(dd)
}

if I use as then what happens is...

Compiler : Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap') at MainKt.main(main.kt:7)

Upvotes: 0

Views: 600

Answers (1)

al3c
al3c

Reputation: 1452

as Int casts something which is already an Int to the type Int.

val x:Any = 5
val xInt = x as Int

.toInt() parses a string that represents an Int.

Upvotes: 1

Related Questions