How to check operators if Scala matches

I send an arithmetic operation like: a + b to my program, inside the program I read every part and set the param variable, x is another constant variable that I have and the operator. The operator will be passed to args (1), and then based on what I have, I want to perform an action using another program. Below is the part of the program that I explained:

if (param != 0){ args(1) match { case + =>val resRDD=sv.apply(sRDD, x:Float=>x + param) case - =>val resRDD = sv.apply(sRDD, x:Float=>x - param) case * =>val resRDD = sv.apply(sRDD, x:Float=>x * param) case / =>val resRDD = sv.apply(sRDD, x:Float=>x / param) case _ => "error" } } 

And I get the following error:

  [error] ')' expected but identifier found. [error] case * =>val resRDD = sv.apply(sRDD, x:Float=>x * param) [error] ^ 

And when I comment on this line, I get a whole bunch of errors, similar to the following for all statements:

 [error] case + =>val resRDD=sv.apply(sRDD, x:Float=>x + param) [error] ^ [error] case + =>val resRDD=sv.apply(sRDD, x:Float=>x + param) [error] ^ 

If i use

  case "+" => //whatever 

I will get the following error:

  [error] not fount: type + 

I am not mistaken in my program!

Thanks!

-1
source share
3 answers

Thanks to all of you, I was able to solve it as follows:

  if (param != 0) { args(1) match { case "+" => val resRDD = sv.apply(sRDD, (x => x + param):Float => Float) case "-" => val resRDD = sv.apply(sRDD, (x => x - param):Float => Float) case "*" => val resRDD = sv.apply(sRDD, (x => x * param):Float => Float) case "/" => val resRDD = sv.apply(sRDD, (x => x / param):Float => Float) case _ => "error" } } 
0
source

Try using a string to match pattern instead of statements: case "+" => for example

+3
source

You must enclose the lambda parameters in parentheses:

 if (param != 0) { args(1) match { case "+" => val resRDD = sv.apply(sRDD, (x: Float) => x + param) case "-" => val resRDD = sv.apply(sRDD, (x: Float) => x - param) case "*" => val resRDD = sv.apply(sRDD, (x: Float) => x * param) case "/" => val resRDD = sv.apply(sRDD, (x: Float) => x / param) case _ => "error" } } 

Here is the official tour entry in the syntax of anonymous functions.

By the way, according to Scala Style Guide, it’s best to backtrack to each level with 2 spaces instead of 4.

I would advise you to read Programming in Scala , which is a great book to start learning about Scala (and moving forward). It will cover all the basic questions regarding syntax, style, and best practices - you will find it useful.

+1
source

Source: https://habr.com/ru/post/987470/


All Articles