Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!