HelloCW
HelloCW

Reputation: 2255

What value will return when I operate transform?.invoke() if transform is null in Kotlin?

I was told that invoke() can be operated safely.

1: What value will return when I operate transform?.invoke() in Code A?
I think the Code val str = transform?.invoke(element) ?: element.toString() is equivalent to the following code, right?

 val temp= transform?.invoke(element)
 val str=temp?: element.toString()

2: I don't know whether .let is another choice in Code B, could you tell me?

Code A

fun <T> Collection<T>.joinToString(
        separator: String = ", ",
        prefix: String = "",
        postfix: String = "",
        transform: ((T) -> String)? = null
): String {
    val result = StringBuilder(prefix)

    for ((index, element) in this.withIndex()) {
        if (index > 0) result.append(separator)
        val str = transform?.invoke(element) ?: element.toString()
        result.append(str)
    }

    result.append(postfix)
    return result.toString()
}

Code B

fun <T> Collection<T>.joinToString(
        separator: String = ", ",
        prefix: String = "",
        postfix: String = "",
        transform: ((T) -> String)? = null
): String {
    val result = StringBuilder(prefix)

    for ((index, element) in this.withIndex()) {
        if (index > 0) result.append(separator)

        var str =element.toString()
        transform?.let{
           str=transform(element)
        }

       result.append(str)
    }

    result.append(postfix)
    return result.toString()
}

Upvotes: 2

Views: 71

Answers (1)

shiftpsh
shiftpsh

Reputation: 1926

?. operator is called the Safe Call Operator.

For transform?.invoke(element), if transform is not null it'll call invoke(element) and return its value; otherwise it'll be null as well.

So yes, it's equivalent since if temp is not null str is transform?.invoke(element), otherwise it's going to be element.toString().


transform?.let{
   str = transform(element)
}

The compiler will assume that transform is not null in let block, since if transform is null, let block will not be executed because you safe-called. so Code B is also an equivalent of Code A.


Read more about null safety in Kotlin:

Also about Smart Casts:

Upvotes: 4

Related Questions