Kotlin Koans—Part 15

Kotlin supports API that is similar to what is offered by Java 8 Streams. In this portion of the Kotlin Koans tutorial, I had to work with filtering and mapping. As an added bonus, I saw a good use case for Kotlin’s operator overloading capabilities and it’s collection transformation capabilities.

Here is the Kotlin code

fun Shop.getCitiesCustomersAreFrom(): Set {
    return customers.map { it.city }.toSet()
}

fun Shop.getCustomersFrom(city: City): List {
    return customers.filter { it.city == city }
}

The first function has us extracting all cities out the customers. In this example, customer has a city property. We can therefore us the map function to drill down to the city property on customer and gather than into a collection. Once we have our customers, we can use the toSet() method to transform the collection into a set.

The second function has us using a predicate to filter customers by city. Kotlin has operator overloading so we can use the == to compare object equality in Kotlin rather than reference equality in Kotlin.

Kotlin has to offer Android developers in this case. Java developers have much of these features as of JDK 8. One thing I noticed in particular was that you do not need to call stream() on collections in Kotlin. I don’t find this to be a huge surprise however. Much of the Java 8 functionality came in the form of the new Streams api, which they attached to the collection framework. Kotlin seems to have built such features directly into the collection classes.

You can click here to see Part 14

Kotlin Koan—Part 13

Kotlin has nice extensions on Collection classes. JDK has provided developers a way to sort collections for a long time now, but often times, it’s done with external classes such as Collections. This puts us in a odd position of using procedural programming when performing operations such as sorting a collection.

A more OOP approach would be to have a sort method directly on a Collection as opposed to passing a collection to an external class with a static method. Kotlin extends Java collections by using its extension feature to complement the collection classes found in JDK.

Here is an example that demonstrates how to sort an ArrayList in Java.

fun task12(): List {
    val lst =  arrayListOf(1, 5, 2)
    lst.sortDescending()
    return lst
}

If all fairness to Java, JDK 8 did address this issue. Here is the equivalent Java code that does the same thing.

public class CollectionSort {
    public List sortList(){
        List lst = Arrays.asList(1, 5, 2);
        lst.sort(Comparator.reverseOrder());
        return lst;
    }
}

I’m not going to complain too much about the Java 8 syntax, but I think sortDescending() and sortAcending() is more readable than Comparator.natualOrder() and Comparator.reverseOrder(). However, the Kotlin approach is much superior to JDK 7 and earlier.

You can read the previous post here.

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 10

This part of the Kotlin Koans tutorial involved extension functions. This is a construct I have never seen in programming before, so it took me a little bit to get an idea of what it is and when to use this feature.

It seems as if the idea here is to add features to a class without have to use inheritence or some sort of delegate object. Here is the Kotlin code.

//This is the class we are adding to
data class RationalNumber(val numerator: Int, val denominator: Int)

//We are adding an r() method to Int which
//returns an instance of RationalNumber
fun Int.r(): RationalNumber = RationalNumber(toInt(), 1)

//We add an r() method to Pair which returns an
//instance of RationalNumber
fun Pair.r(): RationalNumber = RationalNumber(first, second)

The Kotlin documentation has a motivation section that explains the purpose behind extensions. They explain that in many cases in Java, we end up with FileUtils, StringUtils, *Utils classes. In the ideal world, we would want to add features to say the List class directly rather than having a ListUtils class with a bunch of static methods.

We get something like this in JDK8 with default methods that can get placed in an interface. However, that still requires us to extend and interface to add extra methods. Extensions let us work directly on the classes we are already using.

You can click here to see Part 9

Kotlins Koans—Part 8

Kotlin introduces a nullable data type. The idea behind it is to dramatically reduce if not eliminate the NullPointerException. Developers of almost any language have had to fight with some sort of exception that get’s thrown when trying to derefence a null type.

This portion of the Kotlin Koans tutorial has us rewriting the following Java code in Kotlin.

public class JavaCode7 extends JavaCode {
    public void sendMessageToClient(@Nullable Client client, @Nullable String message, @NotNull Mailer mailer) {
        if (client == null || message == null) return;

        PersonalInfo personalInfo = client.getPersonalInfo();
        if (personalInfo == null) return;

        String email = personalInfo.getEmail();
        if (email == null) return;

        mailer.sendMessage(email, message);
    }
}

Readers will see the amount of boilerplate that is in this code. You have three if statements that are dedicated to checking if a reference is null or not.

I do like the @Nullable annotations because it lets me know that these incoming parameters can be null and I need to know to check for a null case. Lombok has a similar @NonNull annotation that does the job of throwing a NullPointerException if the incoming parameters are null.

JDK8 (3rd prior libraries prior to JDK8) did give Java developers an Optional class and JDK7 has the Objects.nonNull method. These classes help with null safety, but at the cost of more boilerplate.

public class Optionals {

    public void sendMessageToClient(Optional clientOptional,
                                    Optional messageOptional,
                                    Mailer mailer){
        clientOptional.ifPresent(client ->
                messageOptional.ifPresent(message -> {
            PersonalInfo personalInfo = client.getPersonalInfo();
            if (nonNull(personalInfo) &&
                    nonNull(personalInfo.getEmail())){
                mailer.sendMessage(personalInfo.getEmail(), message);
            }
        }));
    }
}

Kotlin has a ?: operator that helps with dealing with the NullPointerException.

fun sendMessageToClient(
        client: Client?, message: String?, mailer: Mailer
) {
    message ?: return
    val email = client?.personalInfo?.email ?: return
    mailer.sendMessage(email, message)
}

The Kotlin code does the same thing as the Java code but there are a few things to discuss. When Kotlin parameters have a ? operator, that means they can be a null type. Unlike Java, the Kotlin compiler forces you to address the null case in such variables. I feel this is a super helpful feature because it’s easy to overlook a null case without compiler checks.

By the time we get to mail.sendMessage the variables email and message have to have values or the code will not compile. This is because the previous two lines force us to check for null values and if they are null, return from the function.

You can click here to see Part 7

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

Kotlin Koans—Part 4

Kotlin does indeed use default arguments and named parameters. This was something I really enjoy in Python but isn’t supported in Java.

For those people who aren’t familiar with the term, named arguments is a feature in a programming language where a developer can specify the name of a parameter and assign it a value when calling a function. It helps improve code readability. Here is a little Python to show off named arguments.

def func(arg1, arg2, arg3):
    pass

# Which is more clear?
# Named arguments?
func(arg1=1, arg2=2, arg3=3)

# Non-named arguments?
func(1, 2, 3)

In the above code snippet, the developer calls each argument in the function by it’s name and assigns a value to the parameter. It’s a lot nicer because you can instantly see what each value in the function is doing.

Many people have probably heard of default arugments. This is a feature in many programming languages where a developer can specify a default value for a parameter. When calling the function, the client code can choose to specify a value or just use the default. Here is another little Python teaser.

def func(arg1='Hello World'):
    pass

# Using default
func()

# Using custom value
func('Thunderbiscuit')


Java does not support either of these concepts. It does support function overloading. In this portion of Kotlin Kroans, we have to translate this Java code into Kotlin.

package i_introduction._3_Default_Arguments;

import util.JavaCode;

public class JavaCode3 extends JavaCode {
    private int defaultNumber = 42;

    public String foo(String name, int number, boolean toUpperCase) {
        return (toUpperCase ? name.toUpperCase() : name) + number;
    }

    public String foo(String name, int number) {
        return foo(name, number, false);
    }

    public String foo(String name, boolean toUpperCase) {
        return foo(name, defaultNumber, toUpperCase);
    }

    public String foo(String name) {
        return foo(name, defaultNumber);
    }
}

Readers will notice that the function foo is overloaded three times with different versions specify default arguments. It works, but it's also super verbose. Kotlin cuts through all of that noise. Here is the same code in Kotlin.

fun foo(name: String, number: Int = 42, toUpperCase: Boolean=false): String {
    if (toUpperCase) {
        return name.toUpperCase() + number
    } else {
        return name + number
    }
}

Readers will see that Kotlin is much more consice. One Kotlin function can do the same job as four functions in Java. We can call this function using this code.

fun task3(): String {
    return (foo("a") +
            foo("b", number = 1) +
            foo("c", toUpperCase = true) +
            foo(name = "d", number = 2, toUpperCase = true))
}

In this code snippet, we make four distinct calls to foo. Each time, we only specify the arguments that we need. I am also a huge fan of using the named arguments also. It makes it much easier to read the code.

You can click here to see Part 3 or Part 5

Kotlin Koans—Part 3

The last tutorial’s challange was to take a collection and assemble it into a string using StringBuilder. Java 8 finally gave developers a way to join a String, but Kotlin seems to make it even easier.

This partion of the Kotlin Koans tutorial has us using collection::joinToString. Using Kotlin, we can assemble an entire collection into a String using just one line of code.

fun task2(collection: Collection): String {
    return collection.joinToString(", ", "{", "}")
}

This code is functionally equivalent to what we did in part 2. I also learned a little bit more about the language. Kotlin let’s us have default parameters in our methods. I have to say, while I appreciate Java’s method overloading capabilities, there are times where it’s simplier to use default parameters.

You can click here to see Part 2 or Part 4

Functions—Python

All computer programming languages allow developers to seperate code into reuseable pieces of code called functions. Functions are critical because they allow us to generalize pieces of work into a block of code and reuse that code as many times as needed. When designed well, functions improve code readability by cutting down on the length of the code. We can also debug our code easier because we only have to look in on place for a bug rather than several places.

Demonstration

Let’s begin with a function demonstration.

# A function
def nested_func():
    print('Inside of nested_func()')
    return 'value'


# A function
def func():
    print('Inside of func()')

    val = nested_func()
    print('Back in func(). nest_func() returned {}'.format(val))


# Not a function
if __name__ == '__main__':
    print('Outside of all functions. Calling func()')
    func()
    print('Back from our functions')

This is a block of code that creates two functions. When we run the code, we get this output.

Outside of all functions. Calling func()
Inside of func()
Inside of nested_func()
Back in func(). nest_func() returned value
Back from our functions

Computer programs normally run from top to bottom one line at a time. In the case of this program, the program doesn’t start until we reach if __name__ == '__main__':. This is because Python runtime isn’t going to execute the code inside of nest_func() or func() until the functions are called.

When the code reaches 17, it executes the print statement. The next line, 18, is our first call to a function. We named our function func() in this case. Calling func() causes the program’s execution to jump up to line 9. Once we are at line 9, Python executes the print statement and then moves onto the next line in the function, line 11.

Line 11 creates a variable called val and then calls our next function, nested_func(). The nested_func() function is a function that returns a value. Program execution moves to line 3. Line 3 executes the print statement, and then line 4 returns a String value. The program execution returns back to line 11.

At this point, the variable val has a value stored in it. The program’s execution goes to line 12 and the print statement is executed. Now the program exits the func() function and control returns to line 19. The program executes the final print statement found on line 19 and then exits.

Defining a function

You create functions in Python by using the def keyword followed by the name of the function. After the name of the function, you have an opening parentheses ( followed by a closing parenthese ). You can place any number of variables inside of the parentheses. Here is an example

# Function with arguments
def func(val, val2):
    print(val)
    print(val2)

# Calling the function
func('Hello', 'World')

The name of this function is func. It has two arguments, val and val2. After the colon, you can include any number of statements you would like inside of the function. The function is now a seperate unit of code at this point. This function get’s called by func('Hello', 'World'). Anytime the Python interpreter something like this, it will execute all of the statements inside of func. We do not have to use ‘Hello’ or ‘World’ as the argument either. It’s perfectly ok to do something like func(47, 'Thunderbiscuit').

Optional Arguments

We can specify default values to our functions.

def some_func(arg1='Mickey'):
    print(arg1)

# Prints 'Mouse'
some_func('Mouse')

# Prints 'Mickey'
some_func()

Since this function has optional arguments, we can either pass it our own argument, or we can just use the default. The first call passes ‘Mouse’ to some_func, in which case arg1 = ‘Mouse’. The second call does not specify a value, so arg1 gets the default ‘Mickey’ value.

Recursion Example — Walking a file tree

Many developers use Python as a platform independent scripting language to perform file system operations. Sometimes it’s necessary to walk through a file system. Here is one way to navigate a file system recusively. (Of course, Python has libaries that do this!)

import os

def walk_fs(start_dir):
    # Get a list of everything in start_dir
    contents = os.listdir(start_dir)

    # This stores the output
    output = []

    # Loop through every item in contents
    for f in contents:
        # Use os.path.join to reassmble the path
        f_path = os.path.join(start_dir, f)

    # check if f_path is directory (or folder)
    if os.path.isdir(f_path):
        # Make recusive call to walk_fs
        output = output + walk_fs(f_path)
    else:
        # Add the file to output
        output.append(f_path)

    # Return a list of files in the directory
    return output

if __name__ == '__main__':
    try:
        result = walk_fs(input('Enter starting folder => '))
        for r in result:
            print(r)
    except FileNotFoundError:
    print('Not a valid folder! Try again!')

The key to this is to begin by using os.listdir, which returns a list of every item in a directory. Then we can loop through each item in contents. As we loop through contents, we need to reassemble the full path because f is only the name of the file or directory. We use os.path.join because it will insert either / (unix-like systems) or \ (windows) between each part of the path.

The next statement checks if f_path is a file or directory. The os.path.isdir function is True if the item is a directory, false otherwise. If f_path is a folder, we can make a recursive call to walk_fs starting with f_path. It will return a list of files that we can concat to output.

If f_path is a file, we just add it to output. When we have finished iterating through contents, we can return output. The output file will hold all of the files in start_dir and it’s subdirectorys.