Home > Net >  I want to merge two lists of Mcqs and True false type questions in List of quiz type
I want to merge two lists of Mcqs and True false type questions in List of quiz type

Time:05-26

The data class of Mcqs look like this:

data class Mcqss(
  var answer: String,
  val mcqs: String,
  val option1: String,
  val option2: String,
  val option3: String,
  val option4: String,
  var topicId: String,
  var sequence: String,
)

True false data class:

data class tf(
  val answer: String,
  val question: String,
  val topicId: String,
  val sequence: String,
)

Quiz data class:

data class quiz(
  var topicId: String,
  var sequence: String,
  var mcq_question:String,
  var trf_question:String
)

Function to combine two lists:

fun <T, U> combine(first: ArrayList<Mcqss>, second: ArrayList<tf>): MutableList<Any> {
  val list: MutableList<Any> = first.map { i -> i }.toMutableList()
  list.addAll(second.map { i -> i  })
  return list
}

But when I execute this line it gives me a class cast exception:

val joined: ArrayList<quiz> = combine<Any,Any>(mcqlist, tfs) as ArrayList<quiz>

for (item in joined) {
  item.sequence
}

Any suggestions please.

CodePudding user response:

Please try next code:

fun combine(first: ArrayList<Mcqss>, second: ArrayList<Tf>): ArrayList<Quiz> {
    // I assume the sizes of `first` and `second` lists are the same
    require(first.size == second.size)

    val result = mutableListOf<Quiz>()
    for (i in 0 until first.size) {
        val quiz = Quiz(first[i].topicId, first[i].sequence, ...)
        result.add(quiz)
    }
    return ArrayList(result)
}

val joined: ArrayList<Quiz> = combine(mcqlist, tfs)

I would recommend to name classes starting with a capital letter, e.g. quiz->Quiz.

CodePudding user response:

val mcqlist: List<Mcqss> = ...
val tfs: List<TrueFalse> = ...

val joined = mcqlist   tfs

for (item in joined) {
  if (item is Mcqss) {
    println(item.option1)
  } else if (item is TrueFalse) {
    println(item.question)
  }
}
  • Related