Skip to content

Instantly share code, notes, and snippets.

@optimho
Created January 8, 2022 20:35
Show Gist options
  • Select an option

  • Save optimho/5a909d9bbd057c98ab9e7994276b80d8 to your computer and use it in GitHub Desktop.

Select an option

Save optimho/5a909d9bbd057c98ab9e7994276b80d8 to your computer and use it in GitHub Desktop.
A way of safe casting
import java.time.temporal.TemporalAmount
import kotlin.reflect.typeOf
fun main(args: Array<String>) {
val obj: Any = getStuff("1")
val casted: Int? = obj as? Int
println(casted)
}
fun getStuff(value: String): Any{
return when (value){
"1" -> 88
"2" -> 1.0
"3" -> true
"4" -> "michael"
"5" -> Persons("Monkey")
else -> {-1}
}
}
data class Order (val amount: Int){}
data class Persons(val name:String){}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment