concept true in category kotlin

appears as: true
The Joy of Kotlin

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

The last parameter of the forAll function is a function that should return true for the test to pass. This function can take several arguments which are automatically generated. For example, you can use

To stick with the idea that Empty means optional data, you’d need to first filter the list to remove the Empty elements. But for this, you’d need an isEmpty function in the Result class returning true in the Empty subclass and false in Success and Failure:

The 0 value is a Pair<Result<A>, Int> with the Int value equal to -1 (the first value smaller than 0). Can you use a standard Pair for this? No, you can’t, because it must have a special equals function that returns true when the integer values are equal, whatever the Result<A> is. The complete function is as follows:

fun getAt(index: Int): Result<A> {
    data class Pair<out A>(val first: Result<A>, val second: Int) {
        override fun equals(other: Any?): Boolean = when {
            other == null -> false
            other.javaClass == this.javaClass ->
                            (other as Pair<A>).second == second
            else -> false
        }

        override fun hashCode(): Int =
                first.hashCode() + second.hashCode()
    }

    return Pair<A>(Result.failure("Index out of bound"), index)
        .let { identity ->
            Pair<A>(Result.failure("Index out of bound"), -1).let { zero ->
                if (index < 0 || index >= length())
                    identity
                else
                    foldLeft(identity, zero) { ta: Pair<A> ->
                        { a: A ->
                            if (ta.second < 0)
                                ta
                            else
                                Pair(Result(a), ta.second - 1)
                        }
                    }
            }
        }.first
}

Now the fold automatically stops as soon as the searched-for element is found. You can use the new foldLeft function for escaping any computation with a zero element. (Remember: zero not 0.) But instead of using a zero element, you can use a predicate and make the function return when this predicate returns true: