Scala:为列表中的匿名对象分配名称

我想知道如何通过字段命名列表中的对象

case class age(id: Int,name:String,age:Int)
val people: List[age] = List(age(2,"Angela",31),age(3,"Rick",28))

在这个最小的示例中,我想创建对象Angela和Rick。

我最初的想法:

val objects: List[age] = people.map( x => {val x.name = new age(x.name,x.age) })

但是当然val x.name不起作用,因为您不能在变量名中使用变量名。

这不是项目的实际问题,而是我坚持的概念。

评论
snihil
snihil

在scala中,符号只是一个编译时概念。它们不能用于在运行时创建对象。例如:

object Foo {
  val bar = 3
}

Here, bar doesn't exist at runtime, but rather it is translated into Bytecode before it can be used by another piece of code.

That being said, there might be techniques that allow you do what you want in Scala. I'm thinking of macros for Scala < dotty and >= dotty. Actually, macros are also only available at compile-time, so this might not even be a fit for your problem.

点赞
评论