Question

I'm having trouble attempting to merge a zipped list I've made into a case class. I'm rather new to Scala and can't seem to get my head around the issue. Here's what i have thus far:

type Name = String
type Number = String
type Mark = Int
type Rank = Int
type Nationality = String
val Ran = new scala.util.Random

case class Student(name:Name, id: Number, nat:Nationality)
case class StExam(name:Name,id:Number)
case class StMark(id:Number, mark:Mark)
case class Result(name:Name, mark:Mark, rank:Rank)

These are the pre-defined types and case classes.

def marks(ls:List[String]):List[StMark] = {
  val r = new scala.util.Random
  val k = 1 to 20 map { _ => r.nextInt(100) } 
  k.toList
    val f = ls.zip(k)
    f.toList
    val l:List[StMark] = f
    l.sortBy(x => x.mark)
}

And here is the function that i have written. What i am trying to do is take in a List of type string, create a list of random numbers and then merge the two lists as part of the case class StMark

Was it helpful?

Solution

Aliasing a type like you are doing is a very bad idea. For defaults stick to defaults.

object Test {
  val Ran = new scala.util.Random

  case class Student(name: String, id: String, nat: String)
  case class StExam(name: String, id: String)
  case class StMark(id: String, mark: Int)

  object StMark {
    def apply(tp: (String, Int)): StMark = StMark(tp._1, tp._2)
  }
  case class Result(name: String, mark: Int, rank: Int)

  def marks(ls: List[String]): List[StMark] = {
    val r = new scala.util.Random
    val k = 1 to 20 map { _ => r.nextInt(100) } toList
    val f = ls.zip(k).toList map { (x: (String, Int)) => StMark(x) }
    f.sortBy(_.mark)
  }
}

You are missing something, your toList operations are not performed in place.

f.toList // returns a new object, it is not updating f itself.
// it's useless in your current code.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top