https://kotlinlang.org logo
#android
Title
# android
k

K0NN4

06/13/2019, 4:42 PM
How can i reference the SongName variable in my other object?
Copy code
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        SpotifyService.connect(this) {
            spotifyAppRemote?.let {
                it.playerApi.subscribeToPlayerState().setEventCallback {
                    val track: Track = it.track
                    Log.d("MainActivity", track.name + " by " + track.artist.name)
                    ALabel.text = track.name
                    Blabel.text = track.artist.name
                    var SongName = track.name
                    var SongArtist = track.artist.name
                }
            }
        }
        GeniusApi.PrintSomething()
    }
}
Copy code
object GeniusApi {
    val BASE_URL = "<https://api.genius.com>"
    val SEARCH_URL = BASE_URL + "/search"
    var DATA = SongName@MainActivity

    fun PrintSomething() {
        Log.e("GeniusApi", DATA)
    }
}
t

tseisel

06/14/2019, 2:57 PM
I'm not sure to understand properly, but you can't reference a local variable from anything other than the block where it is defined.
👆 1
k

K0NN4

06/16/2019, 10:27 PM
how could i make that variable "global" then or change my code the way i can use that variable globally
Does "companion objet" help here?
l

louis993546

06/17/2019, 5:41 AM
Technically yes, you can put
SongName
in companion object and make it work
Copy code
class Activity {
    companion object {
        var songName: String = “”
    }
}

object Foo {
    fun printSomething() {
        println(Activity.songName)
    }
}
But the question is “Why would you do that”. Can you just pass the song name as a parameter to the function?
Maybe something like
Copy code
object foo {
    func printSomethingFor(songName: String, lyricsFetched: (String) -> Unit) { /* making API call */ }
}
(Probably with #rx or #coroutines instead of a callback)