如何在Scala中处理复合类型的函数?

时间:2017-09-06 23:42:34

标签: scala

我从Web服务收到一些输入,我需要验证它并返回输入和消息,如果输入无法验证。所以我对如何处理问题并开始实现它有一个可能的想法,但我很快意识到我因为类型而无法做到。所以我尝试用动态语言来做,我查找语言的语法,在10分钟内我有一个实现:

inputDic

所以它可以工作,我可以打印消息,但我想在Scala中实现(实际上,它必须在Scala中,因为我对项目中使用的语言没有发言权)。所以我意识到问题是我不知道val inputDict = Map( "SomeInt" -> (11, (x: Int) => x < 10, "Input should be less than ten"), "SomeString" -> ("Hello", (x: String) => x.length > 10, "Input should be longer than ten characters"), "SomeDateTime" -> (DateTime.now().minusDays(1), (x: DateTime) => x.isAfter(DateTime.now()), "DateTime cannot be before now") ) def genericValidator(dict: Map[String, (Any, Any => Boolean, String)]): Map[String, (Any, String)] = dict.filter { case (_, (value, predicate, _)) => !predicate(value) }.map { case (key, (value, _, message)) => (key, (value, message)) } val result = genericValidator(inputDict) Error:(14, 33) type mismatch; found : scala.collection.immutable.Map[String,(Any, org.joda.time.DateTime with String with Int => Boolean, String)] required: Map[String,(Any, Any => Boolean, String)] val result = genericValidator(inputDict) 的类型应该是什么。我尝试了以下但是没有成功:

radius

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

如果你想让实现尽可能接近原始的Python代码,我会使用类似的东西:

import org.joda.time.DateTime

def genericValidator(dict: Map[String,(Any,Any=>Boolean,String)]) = {
  dict.collect { case (key, (value, predicate, message)) if !predicate(value) => (key, (value,message)) }
}

val inputDict: Map[String,(Any, Any=>Boolean, String)] = Map(
  "SomeInt" -> (11, { case x: Int => x < 10 }, "Input should be less than ten"),
  "SomeString" -> ("Hello", { case x: String =>  x.length > 10 }, "Input should be longer than ten characters"),
  "SomeDateTime" -> (DateTime.now().minusDays(1), { case x: DateTime => x.isAfter(DateTime.now()) }, "DateTime cannot be before now")
)

val result = genericValidator(inputDict)

for ((k2, (v2, m2)) <- result)
  println(m2)