zero_coding
08/29/2020, 7:08 AMclass GenderMapper(val id: String, val description: String)
fun GenderMapper.toGender(): Gender {
val description = this.description
return Gender.new(id) {
this.description = description
}
}jbnizet
08/29/2020, 7:49 AMreturn Gender.new(id) {
this.description = this@toGender.description
}zero_coding
08/29/2020, 8:33 AMzero_coding
08/29/2020, 8:34 AMthis@toGender means?Tobias Berger
08/29/2020, 9:06 AMthis you mean. in the lambda scope you have multiple this values available:
1. in the lambda, which seems to be defined as Gender.() -> Gender you have the Gender object as this
2. in the extension function scope you have the GenderMapper object.
If you just write this it will default to the innermost context. But Kotlin also allows you to access the other scopes. Each scope is given a name, which is by default the method name that comes right before you open the block. So when setting the description here, this givey sou the Gender and this@toGender gives you the GenderMapper.
This naming mechanism can also be used for returning out of lambdas (assuming you're working with inline functions). E.g. if you're inside a lambda for a call inside a forEach loop and want to jump out of this loop run (like continue, you can return@forEach.
If things get too complicated, you can also give each scope a different name like this:
myMultilevelList.forEach outerLoop@{ innerList ->
innerList.forEach {
if (it.hasError) return@outerLoop
}
}Tobias Berger
08/29/2020, 9:08 AMGenderMapper class, I'd suggest putting description in the constructor/`new` function.zero_coding
08/29/2020, 11:12 AM