I think it is worth giving Kotlin a try if only to expand your programming horizons. I hope reading this article will help you leverage your Optional experience to quickly learn Kotlin's null safety features. The initializer, getter, and setter are optional. In our case, we also need to use the safe call operator to skip the calculation for null values: val lengthKotlin: Int? = kotlinNullable?.let Kotlin provides the built-in method let, which we can invoke on any object. One example of this is when we want to use a default value on a non-optional parameter when passing a null value. There are, however, situations where this feature does not help us achieve what we require. If the transformation cannot be performed by a simple method call, then Optional’s map method is happy to take a lambda as well. Kotlin provides us with an option to provide default values in class constructors. Val lengthJava: Optional = javaNullable.map(String::length) To do the same in Kotlin, we can use safe call operator (?.) as demonstrated below: val lengthKotlin: Int? = kotlinNullable?.length Mike Welsh 16 Followers Engineer with a focus on API design and mobile engineering. Refresh the page, check Medium ’s site status, or find something interesting to read. To transform the value inside Optional using the inner value’s method we can apply a method reference to map. Imitating Kotlin With Java Optional by Mike Welsh Better Programming 500 Apologies, but something went wrong on our end. Map Using The Method of The Inner Value’s Type Val javaNullable: Optional = Optional.ofNullable("Java way, can be null as well”) The code below shows both approaches: val kotlinNullable: String? = "Kotlin way, this can be null" In Kotlin, there is no additional overhead. Optional usage requires creating a new object for the wrapper every time some value is wrapped or transformed to another type - with the exclusion of when the Optional is empty (singleton empty Optional is used). The code in the examples is written in Kotlin because the language has all the JDK classes available. In this article, I will try to map methods of Java’s Optional to Kotlin’s similar, scattered language features and built-in functions.
0 Comments
Leave a Reply. |