[英]pattern matching in String Scala
I wrote the code above to define the type of String based on some rules. 我在上面的代码中编写了一些规则来定义String的类型。
def dataType (input:String) : String = input match {
case input if input.startsWith("Q") => "StringType";
case input if (input.startsWith("8") && !(input.contains("F"))) => "IntegerType"
case input if (input.startsWith("8") && (input.contains("F"))) => "FloatType"
case _ => "UnknowType";
}
This code works well , but I want to optimize it by avoiding the use of If satements. 这段代码很好用,但是我想通过避免使用If来优化它。 I want it to be based on pattern matching only without any use of if statements.
我希望它仅基于模式匹配而不使用if语句。 I tried to modify it this way , but it gives me bad results :
我试图以这种方式修改它,但结果却很糟糕:
def dataType (input:String) : String = input match {
case "startsWith('Q')" => "StringType"
case "startsWith('8') && !(contains('F')))" => "IntegerType"
case "startsWith('8') && (contains('F')))" => "FloatType"
case _ => "UnknowType";
}
it always gives me the UnknownType result 它总是给我UnknownType结果
Any help with this please 任何对此的帮助
Best Regards 最好的祝福
Since you are checking for the initial letter and boolean for containing F , you can create Tuple2[Char, Boolean]
of those cases and use it in you match case
as following 由于要检查包含F的首字母和布尔值 ,因此可以创建这些情况的
Tuple2[Char, Boolean]
并在match case
使用它,如下所示
def dataType (input:String) : String = (input.charAt(0), input.contains('F')) match {
case ('8', true) => "FloatType"
case ('Q', _) => "StringType"
case ('8', false) => "IntegerType"
case _ => "UnknowType"
}
And you should be fine 而且你应该没事
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.