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

mike_shysh

11/06/2017, 1:57 PM
Is anyone could help with this: How to write an extensions function if data class is defined in .kt file, not in kotlin separate class
Copy code
fun CustomerInfo.addRandomPartToName(): CustomerInfo {
    val oldItem = this.customerInfo <<<< `this` is not usable
    val newItem = oldItem?.copy(name = oldItem.name + RandomStringUtils.randomAlphabetic(7))
    return this.copy(customerInfo = newItem)
}
m

menegatti

11/06/2017, 2:01 PM
what’s the error message?
it seems to me that
oldItem
should be only
this
as that is the scope of your extension
m

mike_shysh

11/06/2017, 2:03 PM
Copy code
Error:(27, 24) Kotlin: Unresolved reference: customerInfo
Copy code
Error:(29, 22) Kotlin: Cannot find a parameter with this name: customerInfo
customerInfo
is red
val oldItem = this.customerInfo
this.copy(customerInfo = newItem)
m

menegatti

11/06/2017, 2:04 PM
the thing is
this
is already
CustomerInfo
m

mike_shysh

11/06/2017, 2:05 PM
oh sorry, my bad
yeah, data clases names were a bit messed up
m

menegatti

11/06/2017, 2:05 PM
this
will always be the instance of the type to which the extension belongs to
fun String.foo()  = this.append("a")
for instance
m

mike_shysh

11/06/2017, 2:06 PM
thanks, got it
2 Views