Skip to content

Instantly share code, notes, and snippets.

View Temidtech's full-sized avatar
🏠
Working from home

Temidayo Adefioye Temidtech

🏠
Working from home
View GitHub Profile
// Imagine you have code like this:
class Employee {
final double salary;
Employee(this.salary);
}
class SoftwareEngineer extends Employee {
final String level;
SoftwareEngineer(final double salary, this.level) : super(salary);
}
fun main(args: Array<String>) {
 val location: Any = "Code must compile!"
 val safeString: String? = location as? String
 val safeFloat: Float? = location as? Float
 println(safeString)
 println(safeFloat)
 }
 
//Compiler returns this output:
var y = 5 
var x = y as? String 
println(x) //gives a null as a result
var b = 5 
var a = b as String? 
println(a) // Oh my!!! Another crash
var b = null
var a = b as String?
println(a)
var b = null
var a = b as String
println(a) // ops!!! crashes
// 1. Smart cast example
fun getUserName(): String? = ...
val username = getUserName()
if (username != null) {
println(username.length)
}
// 2. Another Example
fun getName(obj: Any?){
if (obj == null || obj !is String)
val soloList: List<Any> = listOf("Wakanda forever!", "Kotlin is fire!",2018,29.3,12.2837827,true)
for(value in soloList) {
when (value) {
is String -> println("String: '$value'. Capitalize :${value.capitalize()}")
is Int -> println("Integer: '$value'")
is Double -> println("Double: '$value'")
is Float -> println("Float: '$value'")
else -> println("Unknown Type")
}
fun main(args:Array<String>){ 
var kingdom:String = "Wakanda" // 1
kingdom = "Zakanda" // 2
println(kingdom)
}
class rand { val random: Int get() = Random().nextInt() }