[英]Best way to implement behavior based in type in scala
In a friendly chat that I was having with a friend during a code review we notice that in the code there was a lot of: 在代码审查期间我与朋友进行的友好聊天中,我们注意到在代码中有很多:
unknownTypeVal match {
case asStr: String => //DO SOMETHING FOR STRING
case asInt: Integer => //DO SOMETHING FOR Integer
case asMyOwnClass: MyOwnClass => //DO SOMETHING FOR MyOwnClass
}
problem that was initially generated by methods that return Any
or Option
and there is no way to remove that because we are using libraries as XPath, and JSONPath, which return instances of Any
or Option
for a provided path. 问题最初是由返回
Any
或Option
的方法生成的,由于我们将库用作XPath和JSONPath,它们无法返回所提供的路径的Any
或Option
实例,因此无法删除它。
I don't want to get into discussions of "preference" , this is not an opinion question, I want to know either by standard defined preferably by Scala, or any other organization of impact, to do this kind of "type checking" in code in a more organized way, we think that this functionality can be reduced to a single function call to a method which contains a map of function and based on "something" (name of the class or something else that I do not know right now) determine how to process such parameter: 我不想讨论“首选项” ,这不是一个意见问题,我想知道是由Scala最好定义的标准还是任何其他影响组织来进行这种“类型检查”。代码以一种更有条理的方式,我们认为该功能可以简化为对包含函数映射并基于“某物”(类名或我现在不知道的其他物)的方法的单个函数调用)确定如何处理此类参数:
process(myAnnonimusVal: Any) = myMapOfFunct(myAnnonimusVal.getClass) //and based on the function that this will return execute such function pasing myAnnonimusVal
what is encouraged to do by Scala devs or Scala community Scala开发人员或Scala社区鼓励做什么
In principle, match
is the cleanest way to execute code conditional on matching the Any type to something else. 原则上,
match
是在将Any类型与其他类型进行匹配的条件下执行代码的最简洁的方法。 Any chain of if-else, instanceOf, etc is bound to turn out to be even more cumbersome and less elegant. if-else,instanceOf等的任何链注定会变得更加麻烦且不太优雅。 A possible exception is a case where you know what the actual type is and can act accordingly, where a direct cast might be permissible.
可能的例外情况是,您知道实际类型是什么,并且可以采取相应措施,可能允许直接强制转换。
That said, if you find yourself making the same matches many times, you might as well encapsulate the match in order to avoid code repetition. 就是说,如果您发现自己多次进行相同的匹配,则最好封装该匹配,以避免代码重复。 A partial function might be exactly what you have in mind here.
部分功能可能正是您在此想到的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.