https://kotlinlang.org logo
#announcements
Title
# announcements
s

sannysanoff

08/15/2017, 3:40 PM
Hi gentlemen! What is idiomatic way of doing this in Kotlin? var s : String = (some long expression) if (s.length > 255) s = s.take(252)+"...";
l

leonardootto

08/19/2017, 4:46 AM
val maxSize = 8 val startPosition = maxSize - 1 print(if (s.length > maxSize) lastPart(startPosition) else s)
fun lastPart(startPosition: Int): String { return (startPosition until s.length).fold(StringBuffer()) { acc, idx -> acc.append(s.take(idx + 1)) }.toString() }
d

dean

08/19/2017, 7:19 AM
Copy code
// might want some error checking
fun String.truncate(maxLen: Int): String =
    if (this.length < maxLen) this else this.take(maxLen-3) + "..."
You can then use
"short".truncate(10) // "short"
"wowthisislong".truncate(10) // "wowthis..."