Home > Back-end >  How to create an array list of a member variable of a dataclass
How to create an array list of a member variable of a dataclass

Time:02-20

I have a dataclass:

data class MoviesInSeries(
    val originalMovieName: String,

// If there's no value of parameter, assign it as null
    val movieInSeries1Name: String? = null,
    val movieInSeries1Date: String? = null,
    val movieInSeries1Rating: String? = null,
    val movieInSeries1Pic: Int? = null,

    val movieInSeries2Name: String? = null,
    val movieInSeries2Date: String? = null,
    val movieInSeries2Rating: String? = null,
    val movieInSeries2Pic: Int? = null,
    )

I've created two objects of it.

fun getRestOfSeriesMovies(): ArrayList<MoviesInSeries> {
    val movieList = ArrayList<MoviesInSeries>()

    val s_gi_joe = MoviesInSeries("G.I. Joe: Retaliation", "G.I. Joe: The Rise of Cobra",
        "2009","Pg-13",  R.drawable.gijtsofmp)
    movieList.add(s_gi_joe)

    val s_gi_joe2 = MoviesInSeries("G.I. Joe: Retaliation2", "G.I. Joe: The Rise of Cobra",
        "2009","Pg-13",  R.drawable.gijtsofmp)
    movieList.add(s_gi_joe)


    return movieList
}

Now I want to create an array list of the originalMovieName member. I'll later use that to check if a certain string is in it. How would I do that?

CodePudding user response:

there's a lot of weird things happening in your model class :

1-

checkIFMovieNameExist(getRestOfSeriesMovies())
fun checkIFMovieNameExist(list: List<MoviesInSeries>,value:String): MoviesInSeries? {
    return list.find { it.originalMovieName == value }
}

2-from time of creation:

data class MoviesInSeries(
    val originalMovieName: String,

// If there's no value of parameter, assign it as null
    val movieInSeries1Name: String? = null,
    val movieInSeries1Date: String? = null,
    val movieInSeries1Rating: String? = null,
    val movieInSeries1Pic: Int? = null,

    val movieInSeries2Name: String? = null,
    val movieInSeries2Date: String? = null,
    val movieInSeries2Rating: String? = null,
    val movieInSeries2Pic: Int? = null,
){
    init {
        names.add(originalMovieName)
    }
companion object {
    private val names: MutableList<String> = mutableListOf()
    fun getMoviesNames():List<String>{
        return names
    }
}
}

then you can check if a name exist in names list in any place in the code

MoviesInSeries("sd1")
MoviesInSeries("sd2")
MoviesInSeries("sd3")
MoviesInSeries("sd4")
println(MoviesInSeries. getMoviesNames().contains("sd1"))
  • Related