'How do I print Kotlin Class properties to Logcat in Android Studio? [closed]
I am writing a simple program to describe the attributes of my favorite song, namely: artistName, songTitle, releaseDate, etc. I have created a class 'FavoriteSong' and added some properties to represent these attributes. When I run the code, I would like the class properties to be printed to Logcat. How can I achieve this?
package com.example.song
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import java.time.LocalDate
import java.time.Month
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Favorite Song
class FavoriteSong {
val artistName: String = "Wale"
val songTitle: String = "My World"
val releaseDate = LocalDate.of(2020, Month.JANUARY, 1)
val songDuration: Float = 3.50f
val genre: String = "Reggae"
}
// Why won't this Log.d() statement work?
Log.d(FavoriteSong)
}
}
Solution 1:[1]
I'm not well-versed in Android anymore (and more specifically I don't recall Log.d()'s signature), but I see several potential problems here:
FavoriteSongis a class, not an object. You need to create an instance of it by calling the constructor:FavoriteSong()(note the parentheses immediately after the class name)- if
Log.d()needs a string, you probably need to call.toString()on yourFavoriteSonginstance. If it acceptsAny, you should be ok as it will most likely calltoString()under the hood - your current definition of
FavoriteSongdoes not overrideAny'stoString()method. You need to either declare anoverride fun toString(): String = ...yourself, or make this class adata classso that it generates one for you automatically
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Silverback |
