In the Kotlin language, how to access a public variable that is in one class, through another class?

Asked

Viewed 87 times

0

WHAT I DID:

I created a class in android studio and I did it using Kotlin, and within this class I created a "public" variable like string, asseguir:

var variavel_de_tipo_public_string : String = "valor_da_variavel"

PROBLEM TO BE SOLVED:

I need to "call" the variable in another class, so that I can take its value and store it in a variable in that other class.

3 answers

1

Considering that it would not be a problem to have a "static" variable in the source class, a solution would be to use "Companion Object":

/**
 * You can edit, run, and share this code. 
 * play.kotlinlang.org 
 */

fun main() {
    var outraClasse = OutraClasse()
    outraClasse.printVariavel()
}

class UmaClasse() {
    companion object { 
        var variavel_de_tipo_public_string : String = "valor_da_variavel"
    }
}

class OutraClasse() {
    var variavel = UmaClasse.variavel_de_tipo_public_string
    
    fun printVariavel() {
        println(variavel)
    }
}

1

You need to get an object from the class it contains variavel_de_tipo_public_string and access this variable from it. For example:

class UmaClasse {
    var variavel_de_tipo_public_string: String = "valor_da_variavel"
}

...

class OutraClasse {
    fun umaFunção() {
        val umObjeto = UmaClasse()

        // leitura
        println(umObjeto.variavel_de_tipo_public_string)

        // escrita
        umObjeto.variavel_de_tipo_public_string = "outro valor"
    }
}

-2

Voce can make the following way

EX

==============

First Class

class Pessoa {
    var nome: String = "Joao"
}

Second Class - Where Voce will use the first object

class Casa {
    fun pessoasNaCasa() {
        val pessoa: Pessoa = Pessoa()

        // leitura e exibicao
        println(pessoa.nome)

        // alterar o valor
        pessoa.nome = "Bruno"
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.