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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


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



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


invoke()



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?


transform?.invoke()


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


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?


.let



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()
}









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

'Series' object is not callable Error / Statsmodels illegal variable name