1. 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



  2. 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. 

    flatMap is extremly usfull when you try to do proper functional programming. In Java it usually means using Streams and Optionals - concepts introduced in version 8. These two types can be thought of as some kind of wrapper over a type, which adds some extra behaviour - Stream<T> wrapps type T allowing to store any number of elements of type T inside, whereas Optional<T> wrapps some type T to implicitly say that the element of that type may or may not be present inside. Both of them share methods map and flatMap. Before we move on, I want to make sure you understand what the map method is doing. It basically allows you to apply the method to the element inside the wrapper and possibly change it’s type:
    Function<String, Long> toLong = Long::parseLong; // function which maps String to Long
    Optional<String> someString = Optional.of("12L");
    Optional<Long> someLong = someString.map(toLong); //aplying the function to the possible String inside
    Stream<String> someStrings = Stream.of("10L", "11L");
    Stream<Long> someLongs = someStrings.map(toLong); //applying the function to all Strings inside

    After applying the function toLong to our wrappers, their inner types changed to the second type of the toLong signature (the result type). 
    Let’s examine the function Long::parseLong. If we call it using a string that is not actually a valid long it will throw NumberFormatException. But what if Java designers decide to implement it so it returns Optional<Long> instead of just Long and removed the exception? Our code for Optional part would look like that:

    Function<String, Optional<Long>> toLongOpt = Long::parseLongOpt;//method I made up
    Optional<String> someString = Optional.of("12L");
    Optional<Optional<Long>> someLong = someString.map(toLongOpt); //:<

    Wow, that is nasty! When we appliednew method to our wrapper, the inner type was changed from String to Optional<Long> (the result type of toLongOpt which we applied). We don’t really need to have a double Optional because just one is perfectly fine. Now, to get the value we need to extract it twice, not mentioning how it would look like when we want to map it again without unwrapping… To restore it to the single type we would need to write a method like this one:

    public static <T> Optional<T> flatten(Optional<Optional<T>> optional) {
        return optional.orElse(Optional.empty());
    }

    This method will flatten our Optional<Optional<T>> to Optional<T> without changing the inner value. The code will look like this:

    Function<String, Optional<Long>> toLongOpt = Long::parseLongOpt;
    Optional<String> someString = Optional.of("12L");
    Optional<Long> someLong = flatten(someString.map(toLongOpt));

    This is exactly what method flatMap is doing. It first applies the function returning another Optional to the inside object (if present) and then flattens the result before returning it, so you don’t have to do it yourself. This is how we can use it:

    Function<String, Optional<Long>> toLongOpt = Long::parseLongOpt;
    Optional<String> someString = Optional.of("12L");
    Optional<Long> someLong = someString.flatMap(toLongOpt);

    For Stream, we can use it in the situation when the function we want to map our elements with, returns the Stream. (example signature: Function<String, Stream<Long>>).

    That’s it. Just remember that flatMap = map + flatten.

    If you want to dive into the topic read about the Functor and Monad concepts and the relationship between them. 
    0

    Add a comment

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