加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

有没有像Scala的AutoMapper?

发布时间:2020-12-16 09:32:50 所属栏目:安全 来源:网络整理
导读:我一直在寻找一些scala流畅的API来映射对象,类似于 AutoMapper。 Scala中有这样的工具吗? 解决方法 我认为在Scala中不太需要像AutoMapper这样的东西,因为如果使用惯用的Scala模型更容易编写和操作,因为您可以使用隐式转换来定义轻松自动平坦化/投影。 例
我一直在寻找一些scala流畅的API来映射对象,类似于 AutoMapper。
Scala中有这样的工具吗?

解决方法

我认为在Scala中不太需要像AutoMapper这样的东西,因为如果使用惯用的Scala模型更容易编写和操作,因为您可以使用隐式转换来定义轻松自动平坦化/投影。

例如,这里是AutoMapper flattening example Scala中的等价物:

// The full model

case class Order( customer: Customer,items: List[OrderLineItem]=List()) {
  def addItem( product: Product,quantity: Int ) = 
    copy( items = OrderLineItem(product,quantity)::items )
  def total = items.foldLeft(0.0){ _ + _.total }
}

case class Product( name: String,price: Double )

case class OrderLineItem( product: Product,quantity: Int ) {
  def total = quantity * product.price
}

case class Customer( name: String )

case class OrderDto( customerName: String,total: Double )


// The flattening conversion

object Mappings {
  implicit def order2OrderDto( order: Order ) = 
    OrderDto( order.customer.name,order.total )
}


//A working example

import Mappings._

val customer =  Customer( "George Costanza" )
val bosco = Product( "Bosco",4.99 )
val order = Order( customer ).addItem( bosco,15 )

val dto: OrderDto = order // automatic conversion at compile-time !

println( dto ) // prints: OrderDto(George Costanza,74.85000000000001)

PS:我不应该用双倍的钱金额…

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读