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

235
Visualizações
How to get value from another class's function in Kotlin

Like

class A {
   public var tip : String = ""
}

class B {
   val tip2 = A().tip
   println(tip2)
}

class C {
   tiper("abc")
   tiper("def")
   tiper("ghi")

   fun tiper(txt) {
      A().tip = txt
      B.showTip()
   }
}

To be brief, I have a class B, which outputs a 'tip'. There is class C, which creates the text for the 'tip'. And I need to send a value from class C to class B. I tried doing it through class A, sending the value there and then reading it in class B to display it. But in this case it just displays the value "", i.e. by default from class A. Why isn't the value passed by class C taken instead?

The above code is greatly simplified and is a hypothetical description of what I actually have in my code. This is just an abstract example.

I'm a terrible Kotlin programmer, I was just asked to do this one job, so I don't know much about it, hope for your help.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You're creating a new object from type A every time you call it's constructor A().

Thus, inside tiper, you're creating an object of type A and setting the tip value on that object instance.

Then however, you create an object of type B which creates a new object of type A internally. This has no link to the first object of type A you've created. Thus, it does not contain the value you wanted to set but rather the default you've set, which is the empty string "".


Keeping close to our example, you can instead adjust the value on the object of type A that is embedded in the object of type B.

class A {
    var tip: String = ""
}

class B() {
    
    val tipHolder = A()

    fun showTip() {
        println(tipHolder.tip)
    }
}

fun tiper(txt: String) {
    val tipPrinter = B()
    tipPrinter.tipHolder.tip = txt

    tipPrinter.showTip()
}

fun main() {
    tiper("abc")
    tiper("def")
    tiper("ghi")
}

However, without more details on the actual problem, it's hard to help you with the underlying problem you're trying to solve, as written by @aSemy in the comment section.

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