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

尝试将我制作的压缩列表合并到案例类中时遇到问题。 我对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)
}

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


像你正在做的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.
链接地址: http://www.djcxy.com/p/68269.html

上一篇: Creating and merging Lists to a case class

下一篇: Deserializing case classes with Map[String,Any] properties with lift