Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

236
Visualizações
In Kotlin, how do you refer to a variable from outside a scoping function when it has the same name as a field in the lambda receiver

In Kotlin, using a scope function such as "with" that allows the this reference inside the block to reference the lambda result, is it possible to reference the outer class member when it has the same name as one of the fields in the result?

eg

data class Person(name: String)
...
class MyClass {
    var name = ""

    with(personRepository.getPerson(personId)) {
        // How do we set the class "name" member - "this.name" or just "name" refers to the scoped object?
        name = this.name // ???
    }

Obviously using a different variable name is the simple workaround but just wondering if there is a syntax for when the variables have the same name

class MyClass {
    var personName = ""
...
    with(personRepository.getPerson(personId)) {
        personName = this.name
    }
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can use a labeled this to refer to the variable in MyClass. Like this:

with(personRepository.getPerson(personId)) {
    this@MyClass.name = name
}
over 4 years ago · Santiago Trujillo Relatório

0

the this refers to the object that you pass. In order for you to refer to the context of your class you would need to use labels like below. Do note that this is an anti pattern. With scoping functions you would only want to apply logic on the object that you are passing or that is the receiver object in scoping functions like let and apply

class MyClass {
    var name: String = ""
    val person = Person("my name")

    fun setName() = with(person) {
       this@MyClass.name = person.name 
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

I would suggest using let{} instead of with{}:

data class Person(name: String)
...
class MyClass {
    var name = ""

    personRepository.getPerson(personId).let {
    name = it.name
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda