![]() In other words, when we want to use NotNullMap, we need a Map instance first. We have seen that we can create a NotNullMap object by passing a Map object to the constructor. The delegation approach is pretty close to our expectations now. So we can access all Map features directly: assertIs>(laptops) Moreover, a NotNullMap instance is still in type Map. As we’ve overridden the get operator, laptops returns a not-null value. Let’s see how this is done: val laptops = object Īs we can see, we can simply use the original map object to construct a NotNullMap instance. Therefore, we can create an anonymous object wrapping the map object and then overload the get operator. Using the getValue() FunctionĪlso, Kotlin allows us to define anonymous objects from scratch conveniently. For simplicity, we’ll use unit test assertions to verify if the value is expected. So next, let’s see if we can get a not-null value from a map in Kotlin. It can be inconvenient, especially when we know the value won’t be null. But after we get a value from a map using the get operator, we must put !! after the value, as the example above shows. It brings many advantages, such as reducing NullPointerExceptions, making code more readable, and so on. Null safety is one of the most significant features of Kotlin. When we try to get a value with a nonexistent key, map returns null, for example: val nullResult = inputMap ![]() This is because the Map‘s get(key) function returns a nullable value. However, we have to use !! after the result variable. In our test above, we verify if the string value with key=3 starts with “ HP …“. But the map style looks natural and improves code readability. Here, it does the same as calling inputMap.get(3).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |