【问题标题】:How To Change Attributes in List of CustomObject in Scala?如何在 Scala 中更改 CustomObject 列表中的属性?
【发布时间】:2016-05-26 13:22:06
【问题描述】:

我有以下案例类

case class BIC( id: Option[Int], name: String, description: Option[String],
                                    bId: Option[Int], amount: BigDecimal,
                                    createdBy: Option[Int], createdAt: Option[DateTime] )

我的 REST-API 网址如下所示

POST    /api/v3/user/2/bid/23/create

现在 userId = 2 和 bId = 23 来自 URL 路径参数 我也有从 POST 请求 JSON 传入的 BIC 列表,其中不包含 userId 和 bId

我是直接将传入的 JSON 注入到 List[BIC] 中,但是这个列表中的所有对象都没有设置 createdBy (userId) 和 bId。

如果我想在 List[BIC] 的每个 BIC 对象中设置这两个参数,我应该遵循什么方法?

            val lsttemp:List[BIC] = bicList
            val lst:List[BIC]
            lsttemp.foreach(x=>{
              x.bId=inId
              x.createdBy = userId
              lst.add(x)
            })

我正在尝试上面的代码,但它不起作用。

【问题讨论】:

    标签: scala functional-programming


    【解决方案1】:

    Case classes 提供copy 方法,帮助您实现目标:

    val lst = bicList.map( _.copy(bId=inId, createdBy = userId))
    

    【讨论】:

    • 谢谢@Sergey Lagutin
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 2011-02-24
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    相关资源
    最近更新 更多