In this article I will try to map methods of Java’s Optional to Kotlin’ssimilar scattered language features and built-in functions. The code in the examples is written in Kotlin, because the language has all the JDK classes available.

Representation

Let’s start with the representation. The Opitonal usage, requires creating a new object for the wrapper every time some value is wrapped or transformed to another type, with exclusion of when the Optional is empty (singleton empty Optional is used). In Kotlin there is no additional overhead, lanuage uses plain old null. The code below shows both approaches:
val kotlinNullable: String? = "Kotlin way, this can be null"
val javaNullable: Optional<String> = Optional.ofNullable("Java way, can be null as well”)

Map using method of inner value’s type

To transform the value inside Optional using the inner value’s method we can apply a method reference to map. To do the same in Kotlin, we can use safe call operator .? as demonstrated below:
val lengthKotlin: Int? = kotlinNullable?.length
val lengthJava: Optional<Int> = javaNullable.map(String::length)

Map using external mapper

If the transformation cannot be performed by simple method call then Optional’smap method is happy to take lambda as well. Kotlin provides built-in method let, which we can invoke on any object. In our case we also need to use safe call operator to skip the calculation for null values:
val lengthKotlin: Int? = kotlinNullable?.let { external.computeLength(it) }
val lengthJava: Optional<Int> = javaNullable.map { external.computeLength(it) }

Filter

In Optionalfilter allows to remove the value inside, if the provided predicate test returns falseKotlin offers two built-in functions with this behaviour - takeIf and takeUntil. First is simialar to the Optional’sfilter, second one drops the value if the predicate returns true - opposite to takeIf. Example code:
val kotlinFiltered: String? = kotlinNullable.takeIf(predicate) 
val kotlinFiltered2: String? = kotlinNullable.takeUnless(predicate) 
val javaFiltered: Optional<String> = javaNullable.filter(predicate)

FlatMap

There is no built-in Kotlin function with the flatMap behaviour because it’s actually not neccassary. Nullability is not represented by a type and simple mapping turns out to be working fine. 

IsPresent

In Kotlin this check can be performed by a simple null comparision:
val kotlinIsNull: Boolean = kotlinNullable != null     
val javaIsNull: Boolean = javaNullable.isPresent()

It is worth to know, that after we do this, compiler is sure that the value is present and allows us to drop all required null checks in the further code (String? becomes String). 
if (kotlinNullable != null) {                    // String?     
    val notNullable: String = kotlinNullable     // String from this line 
}

Get

Both Optional and Kotin approaches discourage users from getting the inside value with the straight call, because it may cause NPEKotlin introduces rude !! operator, which you should use only as a last resort:
val notSafeGetKotlin: String = kotlinNullable!!
val notSafeGetJava: String = javaNullable.get()

OrElse/OrElseThrow

Kotlin introduces elvis operator ?: which allows to set the default value in case of null or throw an excepcion:
val kotlinValue: String = kotlinNullable?: ""
val javaValue: String = javaNullable.orElse("")
val kotlinExc: String = kotlinNullable ?: throw RuntimeException()
val javaExc: String = javaNullable.orElseThrow { RuntimeException() }

Conclusion

I hope reading this article will help you laverage your Optional's experience to quickly learn Kotlin'snull safety features. I think it is worth to give Kotlin a try if only to expand your programming horizonts. 
0

Add a comment

I have recently started implementing different distributed system protocols to get some understanding how they work. I think that using Akka Actors to simulate hosts is a good choice because they are easy to set up. What is more you can kill actors on demand to test some failure scenarios.

When I started working as a Java Developer, me and my teammate got a first task to repair all broken tests (great task for new starters!) in some old project. Replacing some old configuration and upgrading a few libraries helped making the tests status green but there was another problem.

In this article I am going to share some cool features I stumbled upon while coding with Intellij. These are not the most popular/productivity improving ones - for these you should watch this video. 

1.

I have recently pushed very simple Map Reduce concept implementation on my Github account (click). My idea was to focus on the concept and mock the rest.

In this article I will try to map methods of Java’s Optional to Kotlin’ssimilar scattered language features and built-in functions. The code in the examples is written in Kotlin, because the language has all the JDK classes available.

Representation

Let’s start with the representation.

Have you ever scrolled someone’s code and bumped into this weird method called flatMap, not knowing what it actually does from the context? Or maybe you compared it with method map but didn’t really see much difference? If that is the case then this article is for you.

Fact - End-to-end  tests are critical if you want to make sure your software works as it should. To be 100% sure that you covered every (or almost every) possible branch in your business code, it is worth to check what code has been invoked after your E2E suite finished successfully.

Functional Programming in Java

Stream and Optional classes - added to Java 8 - allow you to have some fun with functional programming. The problem is Java still misses quite a lot to be taken as a serious FP language.

In this article, I am going to present you a simple trick that will make using java.util.function.Function.andThen() more useful.

1

Checked exceptions & Java 8

Defining custom exceptions (both checked and unchecked) is a common approach to handling errors in Java applications. It usually leads to creating a new class for every different type of error, marking methods with throws keyword or wrapping code with try-catch blocks.

1
Popular Posts
Popular Posts
About Me
About Me
Labels
Blog Archive
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.