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

Advertisements

2 thoughts on “Kotlin Koans—Part 5”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s