首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >有没有类似于Scala的AutoMapper?

有没有类似于Scala的AutoMapper?
EN

Stack Overflow用户
提问于 2011-07-31 03:36:16
回答 1查看 4K关注 0票数 19

我一直在寻找一些scala fluent API来映射对象-对象,类似于AutoMapper。Scala中有这样的工具吗?

EN

回答 1

Stack Overflow用户

发布于 2011-08-05 16:38:18

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

例如,下面是AutoMapper flattening example的Scala中的等价物

代码语言:javascript
复制
// 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)

附言:我不应该使用双倍的金额…

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6885558

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档