Last active
June 23, 2017 15:18
-
-
Save galex/93d676c572eb985a169cc33c6de2b489 to your computer and use it in GitHub Desktop.
Test to outsmart smart casting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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