避免 Scala 中的类型转换 [英] avoid type conversion in Scala

查看:34
本文介绍了避免 Scala 中的类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的要求,其中数据作为名称->来自服务的值对,并且所有名称->值类型仅为字符串(实际上并非如此,但这就是数据的存储方式)

I have this weird requirement where data comes in as name ->value pair from a service and all the name-> value type is string only (which really they are not but that's how data is stored)

这是一个简化的说明.

case class EntityObject(type:String,value:String)

EntityObject("boolean","true")

现在当获取该实体对象时,如果类型是boolean",那么我必须确保值不是其他任何东西,而是布尔值,所以首先输入并检查值并将值转换为该类型.例如,在这种情况下,检查值是布尔值,因此必须将字符串值转换为布尔值以进行验证.如果它是布尔值之外的其他任何东西,那么它应该失败.

now when getting that EntityObject if type is "boolean" then I have to make sure value is not anything else but boolean so first get type out and check value and cast value to that type. e.g in this case check value is boolean so have to cast string value to boolean to validate. If it was anything else besides boolean then it should fail.

例如如果数据如下所示,转换将失败,它应该向调用者报告这个错误.

e.g. if data came in as below, casting will fail and it should report back to the caller about this error.

EntityObject("boolean","1")

由于这个奇怪的要求,它强制在验证代码中进行类型转换,这看起来不优雅并且不利于类型安全编程.有什么优雅的方法可以在 Scala 中处理这个问题(可能是一种更安全的方式)?

Due to this weird requirement it forces type conversion in validation code which doesn't look elegant and against type safe programming. Any elegant way to handle this in scala (may be in a more type safe manner)?

推荐答案

在这里,我要传达从 Miles Sabin 的推文中获取的关于异源映射的想法(请参阅 github 上的这个要点.)如果您提前知道对象映射名称的类型,您可以使用一个漂亮的小技巧,它涉及依赖类型.等等,因为这是一次疯狂的旅程:

Here is where I'm going to channel an idea taken from a tweet by Miles Sabin in regards to hereogenous mappings (see this gist on github.) If you know the type of object mapping names a head of time you can use a nifty little trick which involves dependent types. Hold on, 'cause it's a wild ride:

trait AssocConv[K] { type V ; def convert: String => V }

def makeConv[V0](name: String, con: String => V0) = new AssocConv[name.type]{
  V = V0
  val convert = con
}

implicit val boolConv = makeConv("boolean", yourMappingFunc)

def convEntity(name: String, value: String)(implicit conv: AssocConv[name.type]): Try[conv.V] = Try{ conv.convert(value) }

我还没有测试过这个,但它应该"工作.我还将它包含在 Scala Try 中,以便它捕获您的转换函数抛出的异常(以防您将 _.toInt 作为转换器.)

I haven't tested this but it "should" work. I've also enclosed it in a Scala Try so that it catches exceptions thrown by your conversion function (in case you're doing things like _.toInt as the converter.)

这篇关于避免 Scala 中的类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆