Home > Mobile >  How to get value from another class's function in Kotlin
How to get value from another class's function in Kotlin

Time:02-23

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.

CodePudding user response:

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.

  • Related