![]() ![]() Kotlin provides the built-in method let, which we can invoke on any object. If the transformation cannot be performed by a simple method call, then Optional’s map method is happy to take a lambda as well. 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 ![]() To transform the value inside Optional using the inner value’s method we can apply a method reference to map. 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. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |