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

mg6maciej

04/22/2017, 2:07 PM
Any way to force use of named parameters on
copy
for certain data classes? I have a class where first two props are `Int`s and wanted to change the second, but forgot to use name of property. Found after like 5 minutes.
s

snrostov

04/22/2017, 2:17 PM
Copy code
class Barrier internal constructor()

val barrier_ = Barrier()

data class Ugly(val i: Int, val j: Int) {
    fun safeCopy(barrier: Barrier = barrier_, i: Int = this.i, j: Int = this.j)
            = this.copy(i = i, j = j)
}

fun main(args: Array<String>) {
    Ugly(1, 2).safeCopy(1, 2) // compile time error
    Ugly(1, 2).safeCopy(i = 1, j = 2)
}
m

mg6maciej

04/22/2017, 2:24 PM
Interesting, but indeed ugly.
r

Ruckus

04/22/2017, 4:14 PM
You could use the
Nothing
hack (
vararg barrier: Nothing
as the first parameter)
👍 1
2 Views