Reputation:
I wrote the code above to define the type of String based on some rules.
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. I want it to be based on pattern matching only without any use of if statements. 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
Any help with this please
Best Regards
Upvotes: 2
Views: 274
Reputation: 41957
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
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
Upvotes: 4