创建列表并将其合并到案例类

时间:2013-11-10 15:44:18

标签: scala case-class

我在尝试将我制作的压缩列表合并到案例类时遇到了麻烦。我对Scala很陌生,似乎无法理解这个问题。这是我到目前为止所拥有的:

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)

这些是预定义的类型和案例类。

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)
}

这是我写的功能。我想要做的是接受一个类型字符串列表,创建一个随机数列表,然后将两个列表合并为案例类StMark的一部分

1 个答案:

答案 0 :(得分:1)

像你一样对type进行别名是一个非常糟糕的主意。 默认设置为默认值。

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)
  }
}

您遗失了某些内容,未执行toList次操作。

f.toList // returns a new object, it is not updating f itself.
// it's useless in your current code.