首页 > 解决方案 > How can I convert a list to string

问题描述

data class Movie( 
    @SerializedName("movie_name")
    val movieName : String
    @SerializedName("genres")
    val movieGenre : List<String>){}

How can I convert a list to string created every object in this data class

标签: androidlistkotlin

解决方案


You can use additional property in Movie class to convert list to string, e.g. val genre:

data class Movie(
        @SerializedName("movie_name")
        val movieName: String,
        @SerializedName("genres")
        val movieGenre: List<String>
) {
    val genre: String
        get() = buildString { // builds new string using append() method on each item of movieGenre
            movieGenre.forEach { append(it) }
        }

}

Here is how to access it:

val movie: Movie = getMoviewFromInternet()
val movieGenre: String = movie.genre

推荐阅读