我一直在寻找一些scala fluent API来映射对象-对象,类似于AutoMapper。Scala中有这样的工具吗?
发布于 2011-08-05 16:38:18
我认为在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)
附言:我不应该使用双倍的金额…
https://stackoverflow.com/questions/6885558
复制相似问题