concept List in category kotlin

appears as: List, List
Functional Programming with Kotlin

This is an excerpt from Manning's book Functional Programming with Kotlin.

The example takes two parameters: a CreditCard, and the Int number of coffees to be purchased. After the Coffees have been successfully purchased, they are placed into a List data type. The list is initialized using the List(n) { buyCoffee(cc) } syntax, where n describes the number of coffees, and { buyCoffee(cc) } a function that is used to initialize each element of the list.

An unzip is then used to destructure the list of pairs into two separate lists, each representing one side of the Pair. Destructuring is the process of extracting values from a complex data type. We are now left with the coffees list being a List<Coffee>, and charges being a List<Charge>. The final step involves reconstructing the data into the required output. This is done by constructing a Pair of List<Coffee> mapped to the combined Charges for all the Coffees in the list. reduce is an example of a higher-order function, which will be properly introduced in chapter 2.

Let’s look first at the definition of the data type, which begins with the keywords sealed class. Usually, we introduce a data type with the class keyword. Here we’re declaring a class, called List, with no instance methods on it. Adding sealed in front of the class declaration means that all implementations must be declared in this file. A sealed class is also abstract by default, so can not be instantiated by itself. There are two implementations, or data constructors, of List declared next, to represent the two possible forms a List can take. As the figure shows, a List can be empty, denoted by the data constructor Nil, or it can be nonempty, denoted by the data constructor Cons (traditionally short for construct). A nonempty list consists of an initial element, head, followed by a List (possibly empty) of remaining elements (the tail).

Figure 3.1. The singly linked list, each tail links to the next list element.
Singly lined list

Just as functions can be polymorphic, data types can be as well, and by adding the type parameter <out A> after sealed class List and then using that A parameter inside of the Cons data constructor, we declare the List data type to be polymorphic in the type of elements it contains, which means we can use this same definition for a list of Int elements (denoted List<Int>), Double elements (denoted List<Double>), String elements (List<String>), and so on (the out indicates that the type parameter A is covariant—see sidebar “More about variance” for more information).

Up to this point we have focused our attention on the definition of the most basic functional data structure, the singly linked list. Having this definition isn’t of much use unless we actually start doing something with it. In this section, you will learn to apply the technique of matching, in order to interpret and process the List that was defined in section 2.1.

Listing 3.2. Companion object inside sealed definition of List data type
sealed class List<out A> { #1

    companion object { #2

        fun <A> of(vararg aa: A): List<A> { #3
            val tail = aa.sliceArray(1 until aa.size)
            return if (aa.isEmpty()) Nil else Cons(aa[0], of(*tail))
        }

        fun sum(ints: List<Int>): Int =
            when (ints) {
                is Nil -> 0
                is Cons -> ints.head + sum(ints.tail)
            }

        fun product(doubles: List<Double>): Double =
            when (doubles) {
                is Nil -> 1.0
                is Cons ->
                    if (doubles.head == 0.0) 0.0
                    else doubles.head * product(doubles.tail)
            }

    }
}

In order to add some behaviour to the List type, a companion object is added to the body of its definition. Any functions defined within the companion object block can be called like you would a static method in Java. For instance, the of method can be used in the following way to construct a new List from the parameters passed in:

Firstly, let’s revisit the sum function that we wrote in the companion object of our List class:

Listing 3.7. Simple when matching in List companion object
fun sum(xs: List<Int>): Int = when (xs) {
    is Nil -> 0
    is Cons -> xs.head + sum(xs.tail) #1
}

The most noticeable problem is that we are accessing the value xs inside the evaluation of our branch logic by members as xs.head and xs.tail. Notice that xs is declared as a List, which has no head or tail. The fact that List has been smartcast to Cons is never explicitly stated, which causes confusion about the ambiguous type of xs.

If Kotlin supported pattern matching as provided by other languages, it would allow us to express this as in the following Kotlin pseudocode: .Pattern matching in List companion object using pseudocode

The Joy of Kotlin

This is an excerpt from Manning's book The Joy of Kotlin.

Here I’m using the standard Kotlin fold function working on Kotlin lists. If you prefer to use the List you developed in chapter 5, it would be

Folding a list involves starting with a value and composing it successively with each element of the list. This obviously takes an amount of time proportional to the length of the list. Is there any way to make this operation faster? Or, at least, is there a way to make it appear faster? As an example of a fold application, you created a length function in List in chapter 5 (exercise 5.10) with the following implementation:

fun <A, B> unzip(list: List<Pair<A, B>>): Pair<List<A>, List<B>> =
    list.coFoldRight(Pair(List(), List())) { pair ->
        { listPair: Pair<List<A>, List<B>> ->
            Pair(listPair.first.cons(pair.first),
                 listPair.second.cons(pair.second))
        }
    }
Kotlin in Action

This is an excerpt from Manning's book Kotlin in Action.

The last function is no more complex than lastChar for String, discussed in the previous section: it’s an extension on the List class. For max, we show a simplified declaration (the real library function works not only for Int numbers, but for any comparable elements):

Generics allow you to define types that have type parameters. When an instance of such a type is created, type parameters are substituted with specific types called type arguments. For example, if you have a variable of type List, it’s useful to know what kind of things are stored in that list. The type parameter lets you specify exactly that—instead of “This variable holds a list,” you can say something like “This variable holds a list of strings.” Kotlin’s syntax for saying “a list of strings” looks the same as in Java: List<String>. You can also declare multiple type parameters for a class. For example, the Map class has type parameters for the key type and the value type: class Map<K, V>. We can instantiate it with specific arguments: Map<String, Person>. So far, everything looks exactly as it does in Java.

Just as in Java, you declare a Kotlin generic class or interface by putting angle brackets after the class name and the type parameters in the angle brackets. Once you do that, you can use the type parameters in the body of the class, just like any other types. Let’s look at how the standard Java interface List can be declared in Kotlin. To simplify it, we’ve omitted the majority of the methods:

interface List<T> {  #1     operator fun get(index: Int): T   #2     // ... } #1 - The List interface defines a type parameter T. #2 - T can be used as a regular type in an interface or a class.

Later in this chapter, when we get to the topic of variance, you’ll improve on this example and see how List is declared in the Kotlin standard library.

Just as in Java, Kotlin’s generics are erased at runtime. This means an instance of a generic class doesn’t carry information about the type arguments used to create that instance. For example, if you create a List<String> and put a bunch of strings into it, at runtime you’ll only be able to see that it’s a List. It’s not possible to identify which type of elements the list was intended to contain. (Of course, you can get an element and check its type, but that won’t give you any guarantees, because other elements may have different types.)

Figure 9.3. At runtime, you don’t know whether list1 and list2 were declared as lists of strings or integers. Each of them is just List.