https://kotlinlang.org logo
Title
m

matt tighe

03/19/2019, 6:13 PM
is there a way to skip the intermediate assignment here?
data class VersionCode(val code: String) {
    val major: Int
    val minor: Int
    val patch: Int
    init {
        val (first, second, third) = code.substringAfter('v').split('.')
        major = first.toInt()
        minor = second.toInt()
        patch = third.toInt()
    }
}
j

Joe

03/19/2019, 6:28 PM
I don't believe there is
b

bbaldino

03/19/2019, 6:33 PM
would definitely be nice to have more flexibility around destructuring (like being able to use existing variables)
n

Nikky

03/19/2019, 6:34 PM
how about
val (majro, minor, patch) = code.substringAfter('v').split('.').map { it.toInt() }
m

matt tighe

03/19/2019, 7:46 PM
that would work, but wouldn’t the variables become locally scoped to the init block?
s
a

Al Warren

03/20/2019, 12:30 AM
How about an extension function?
data class VersionCode(val major: Int, val minor: Int, val patch: Int)

fun String.versionCode(): VersionCode {
    var major = 0
    var minor = 0
    var patch = 0
    val versionString = this.substringAfter('v')
    if (versionString.isNotEmpty()) {
        val parts = versionString.split('.')
        major = Integer.valueOf(parts[0])
        minor = if(parts.size > 1) Integer.valueOf(parts[1]) else 0
        patch = if(parts.size > 2) Integer.valueOf(parts[2]) else 0
    }
    return VersionCode(major, minor, patch)
}

val text = "v1.2.3"
println(text.versionCode())
// output:
// VersionCode(major=1, minor=2, patch=3)