https://kotlinlang.org logo
#getting-started
Title
# getting-started
z

zero_coding

08/29/2020, 7:08 AM
Hi all Could someone please tell me, how can I make the following code more elegant:
Copy code
class GenderMapper(val id: String, val description: String)

fun GenderMapper.toGender(): Gender {
    val description = this.description
    return Gender.new(id) {
        this.description = description
    }
}
j

jbnizet

08/29/2020, 7:49 AM
You can use
Copy code
return Gender.new(id) {
        this.description = this@toGender.description
    }
z

zero_coding

08/29/2020, 8:33 AM
Could you please explain the code
what does
this@toGender
means?
t

Tobias Berger

08/29/2020, 9:06 AM
It tells the compiler which
this
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:
Copy code
myMultilevelList.forEach outerLoop@{ innerList ->
    innerList.forEach {
       if (it.hasError) return@outerLoop
    }
}
👍 1
About your original question: If you have control over the
GenderMapper
class, I'd suggest putting
description
in the constructor/`new` function.
z

zero_coding

08/29/2020, 11:12 AM
@Tobias Berger Could you please show me, how to do it?
2 Views