Kotlin Koans—Part 19

This section of the Kotlin Koans tutorial continued onward with Kotlin’s collection API enhancement. The challenge in this section use to total the price of all products a customer purchased. Here is the code

fun Customer.getTotalOrderPrice(): Double {
    // Return the sum of prices of all products that a customer has ordered.
    // Note: a customer may order the same product for several times.
    return orders.sumByDouble { it.products.sumByDouble { it.price } }
}

The collection API in Kotlin has a sumByDouble method, which takes a lambda expression. The lambda let’s developers chain function calls. In this case, each Customer had a collection of Products in each Order. To get the price of all Products ordered, I needed the sum of the price of all products in a order. This was easy enough to do because I just made a nested call to sumByDouble on it.products and then told it to sum on it.price.

Here is Java code that solves the same problem.

public static double getTotalOrderPrice(Customer customer){
    return customer
            .getOrders()
            .stream()
            .mapToDouble(
                    order -> order.getProducts()
                                    .stream()
                                    .mapToDouble(Product::getPrice)
                            .sum())
            .sum();
}

You can click here to see Part 18

Advertisements

Kotlin Koans—Part 12

The last part of the Kotlin Koans tutorial had me use Object Expressions to sort an ArrayList. I observed that this could have been done with a lambda expression and I was correct.

This portion of the tutorial discusses implementing an interface with one abstract method. Kotlin calls such interfaces a SAM interface (Single Abstract Method). Whenever a developer is working with a SAM interface, they are free to use a lambda expression rather than an Object Expression.

Here is the Kotlin code that uses a lambda expression

fun task11(): List {
    val arrayList = arrayListOf(1, 5, 2)
    Collections.sort(arrayList, { x, y -> y.compareTo(x) })
    return arrayList
}

I should point out that Java 8 supports lambda expressions now also. Java calls SAM interfaces Functional interfaces. You can even add a @Functional annotation to such interfaces in Java.

I don’t see any huge advantage to Kotlin lambdas over Java ones at this point. Of course, Android developers may appreciate Kotlin’s lambda support.

You can view part 11 here.

Kotlin Koans—Part 5

Many modern programming lanugages have support for functional programming. I remember when Java got support for functional programming in JDK8. I have to say it was awesome to finally get support for functional programming.

Of course, Java has supported functional programming to a certain degree for a while now through anonymous inner classes. The syntax was verbose…

public class Window extends JFrame {
    
    public Window(){
        JButton jButton = new JButton("Button");
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Clicked");
            }
        });
    }
}

Java 8 simplified this mess when it officially supported functional programming.

public class Window extends JFrame {

    public Window(){
        JButton jButton = new JButton("Button");
        jButton.addActionListener(e -> System.out.println("Clicked"));
    }
}

Readers can see that the above code is far more consise than the previous example so many Java developers, including myself, were greatful for the change. Android developers weren’t so lucky and unless things have changes, Android developers still have to live with anonymous inner class syntax.

That is until Kotlin came along and is now supported for Android. In this portion of the Kotlin Koans tutorial, I had to rewrite this Java code into Kotlin.

public class JavaCode4 extends JavaCode {
    public boolean task4(Collection collection) {
        return Iterables.any(collection, new Predicate() {
            @Override
            public boolean apply(Integer element) {
                return element % 42 == 0;
            }
        });
    }
}

Of course, JDK 8 developers get the Stream API and lambda syntax, while Android developers were out of luck. Here is the equivalent Kotlin code.

fun task4(collection: Collection): Boolean{
    return collection.any { element -> element % 42 == 0 }
}

You can click here to see Part 4