the error is "Error:(20, 35) Kotlin: Type mismatch...
# getting-started
f
the error is "Error:(20, 35) Kotlin: Type mismatch: inferred type is (Int) -> Int but ((Int) -> CharSequence)? was expected". Should I explicitly convert that to a CharSequence? Why? 🤔
z
the definition of joinToString takes a lambda of type (T) -> CharSequence, so yeah, you have to return a String (CharSequence).
Copy code
myArray.joinToString { (it*2).toString() }
✔️ 1
t
Kotlin doesn't have implicit casts
f
so bad, that's pretty ugly.
println (mySecondArray.joinToString { (it*2).toString() } )
this works. But stating "joinToString" and then casting toString again doesn't look very kotlinish. Hope they'll fix that 😄
h
It'd be pretty easy to create your own
joinToString
extension that works the way you describe
Assuming your data type is
Array<Int>
, you could create something like this:
Copy code
fun Array<Int>.joinToString(separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((Int) -> Int)): String {
    return joinTo(StringBuilder(), separator, prefix, postfix, limit, truncated) { n -> transform.invoke(n).toString() }.toString()
}
Which would allow you to do
println (myArray.joinToString { it*2 } )
like you want
a
^ at that point I'd argue it's better to do Any than Int specifically
h
Sure