Skip to content

Instantly share code, notes, and snippets.

@galex
Last active June 23, 2017 15:18
Show Gist options
  • Save galex/93d676c572eb985a169cc33c6de2b489 to your computer and use it in GitHub Desktop.
Save galex/93d676c572eb985a169cc33c6de2b489 to your computer and use it in GitHub Desktop.
Test to outsmart smart casting
package il.co.kotlintlv.intro
var switch : Boolean = true
class Address(val street: String)
class Person {
val age: Int
val address: Address?
get() {
if(switch) {
switch = false
return field
} else {
switch = true
return null
}
}
constructor(age: Int, address: Address?) { // don't do this, use primary constructor
this.age = age
this.address = address
}
}
fun main(args: Array<String>) {
val address = Address("Ygal Alon")
val person = Person(32, address)
if(person.address != null) {
print(person.address.street) // compile time error: Smart cast to 'Address' is impossible, because 'person.address' is a property that has open or custom getter
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment