Chapter 8 - Errata

You can also pass a number into the constructor for these types, for example, to create an array of zeros.
val zeros = DoubleArray(4) // 0.0, 0.0, 0.0, 0.0

The text implies the example will show passing a default value, but the code example does not do this (the 4 is the length of the array, not the default value). This example happens to work because the default value, if one is not provided, is zero. The example should be changed to show a non-zero example and passing that value in the constructor.

Challenge Two solution at the end of the chapter seems to be wrong.

This is the solution given:

  // Challenge 2 - Write a function that removes the first occurrence of a given integer from a list of integers. This is the signature of the function:
  // fun removeOne(item: Int, list: List<Int>): List<Int>

  fun removeOne(item: Int, list: List<Int>): List<Int> {
    val mutableList = list.toMutableList()
    return mutableList.toList()
  1. This is the documentation for remove:
    remove - Kotlin Programming Language
    Note for MutableList this is actually deprecated,
    Deprecated: Use removeAt(index) instead.
    In Kotlin one should use the MutableList.removeAtfunction instead.

Both for .remove and .removeAt, the function does not do what the challenge is asking for. The function removes the item at the provided index.

So if your List is (3, 3, 3, 3, 4, 4, 0, 9) and you call the function to remove 4, according to the challenge question the function should return (3, 3, 3, 3, 4, 0, 9)

But what the provided solution does is remove an item at a certain index, not the provided integer. So the solution given, gives the wrong answer in this case. It will remove the fourth item in the list, not the first occurrence of the integer 4, giving (3, 3, 3, 4, 4, 0, 9)

What the solution should do, is iterate through the list until it finds a match for the provided argument, then remove that item, regardless of the index

@abunur Thank you for the heads up - much appreciated! I will forward this to the book team.

Thanks for the feedback, @abunur! I believe the solution to Challenge Two is actually correct.

The remove function being used in the solution is this one, which is on the same page you linked to:

fun <T> MutableCollection<out T>.remove(element: T): Boolean
Removes a single instance of the specified element from this collection, if it is present

For example, running the following code in the Kotlin playground,

val a = mutableListOf(1, 2, 4, 5, 6, 7, 4, 5)

results in the output [1, 2, 5, 6, 7, 4, 5]. The first occurrence of 4 (at index 2) is removed.