Because we can’t store null into ints and other primitive types, this declaration is illegal in Kotlin. Also, since this is a lateinit variable, Kotlin needs to use null as a special value to represent uninitialized cases. Now, let’s see what’s wrong with the following declaration: private lateinit var x: Intīased on what we learned so far, Kotlin will compile x as an int under the hood. That is, even though we can re-assign lateinit vars to something else, we can’t set them to null explicitly, as it has a special meaning and is reserved for that. The bottom line is, Kotlin is using null as a special value to determine if a lateinit property is initialized or not. If we fail to initialize the property, the runtime will throw an exception once we try to read its value. To overcome this limitation, Kotlin provides lateinit variables, which can be left uninitialized at first: lateinit var userService: UserServiceīasically, here we ‘re telling the compiler that we know we didn’t initialize this variable right away, but we promise to do so as soon as possible. However, we should deal with the awkwardness of nullable types (null-safe operators and so on) every time we’re going to use the variable. One approach to fix this is using nullable types: val userService: UserService? = null The above example won’t even compile because we’re not initializing a non-nullable property. For instance, that can be the case when we’re using a particular dependency injection approach or setup methods in testing frameworks: val userService: UserService // won't work Unfortunately, sometimes it may not be possible or convenient to do that. In Kotlin, we should always initialize non-null properties in the constructor using a property initializer.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |