mrc*_*ori 19 mapping scala automapper mapper
我一直在寻找一些用于映射object-object的scala流畅API,类似于AutoMapper.Scala中有这样的工具吗?
par*_*tic 12
我认为在Scala中不太需要类似AutoMapper的东西,因为如果使用惯用的Scala模型更容易编写和操作,并且因为您可以使用隐式转换轻松定义自动展平/投影.
例如,这里是AutoMapper展平示例的 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)
Run Code Online (Sandbox Code Playgroud)
PS:我不应该使用Double for money amount ...
我同意@paradigmatic,的确,使用Scala可以使代码更加简洁,但是有时您会发现自己在看起来非常相似的case类之间进行映射,这只是浪费了击键次数。
我已经开始着手解决这个问题的项目,您可以在这里找到它:https : //github.com/bfil/scala-automapper
它使用宏为您生成映射。
目前,它可以将案例类映射到原始案例类的子集,可以处理可选字段,可选字段以及其他次要内容。
我仍在尝试弄清楚如何设计api以支持使用自定义逻辑重命名或映射特定字段,对此的任何想法或输入都将非常有帮助。
现在可以将其用于某些简单情况,当然,如果映射变得非常复杂,最好手动定义映射。
Mapping在任何情况下,该库还允许在案例类之间手动定义类型,这些类型可以作为隐式参数提供给AutoMapping.map(sourceClass)or sourceClass.mapTo[TargetClass]方法。
更新
我刚刚发布了处理Iterables,Maps并允许传递动态映射的新版本(例如,支持重命名和自定义逻辑)
| 归档时间: |
|
| 查看次数: |
3238 次 |
| 最近记录: |