gpt4 book ai didi

scala - 是否有类似适用于Scala的AutoMapper?

转载 作者:行者123 更新时间:2023-12-03 12:51:42 24 4
gpt4 key购买 nike

我一直在寻找一些用于映射对象-对象的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:我不应该将Double用作金额...

关于scala - 是否有类似适用于Scala的AutoMapper?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6885558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com