![]() ![]() Therefore, constructor of Mercedes references a yet-uninitialized LewisHamilton variable, and leads to a null value being stored in a non-nullable variable. Its constructor references another lazy variable Mercedes, whose constructor has a circular reference to LewisHamilton. LewisHamilton gets initialized upon its first-access in main. If you run this example on Kotlin Playground, it produces the following output: Driver(name=Sir Lewis Hamilton, teamId=merc)Ī null value snuck into a non-nullable type. Val Mercedes: Team = Team( "merc", listOf(Drivers.LewisHamilton))Īlthough innocuous at first glance, this code breaks Kotlin's non-nullable types. Val LewisHamilton: Driver = Driver( "Sir Lewis Hamilton", ) They break code at runtime, and are difficult to guard against at compile time.Ĭonsider the following example: data class Driver( val name: String, val teamId: String)ĭata class Team( val id: String, val drivers: List) ![]() Breaking Kotlin's Null-Safety with Circular ReferencesĬircular object references can be dangerous.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |