JKC JKC - 2 months ago 22
Scala Question

How to pass a Function name to a Case-Match statement in Scala

I am a newbie to Scala Programmaing and trying to create a Case-Match or Switch-Case statement which inturn invokes different functions based on the input value.

For example please see the sample code snippet. Hope it explains what i intended to do

def getValue(x: Any):String = x match {
case "Value1"=> Function1(int)
case "Value2"=> Function2(int)
case _ => println("This is an invalid value")
}

def Function1(int) {
Do Something
}

def Function2(int) {
Do Something
}


When I give like this, I am getting an error as shown below :

Error:(26, 34) type mismatch;
found : Unit
required: String
case "Value1"=> Function1(int)


Edited :
Modified the return type of getValue to be a "Unit" instead of "String". Now this error is resolved but I am getting the following error message


Error:(26, 22) forward reference extends over definition of value
spark
case "Value1"=> Function1(int)


Modified code snippet

def getValue(x: Any):Unit = x match {
case "Value1"=> Function1(int)
case "Value2"=> Function2(int)
case _ => println("This is an invalid value")
}

def Function1(int) {
Do Something
}

def Function2(int) {
Do Something
}


I resolved this error by keeping the declaration of spark variable at the end of the code.

Answer Source

The problem is that your Function1 and Function2 (horrible names!) return Unit, and getValue is declared to return a String

A declaration of a function looks like def functionName(args): ReturnType = { ... }

Some parts of this can be omitted, and then defaults are assumed. In your case, you omitted the ReturnType declaration, and (more importantly) the = sign. When there is no = before the function body, the function will always return Unit. If you want it to return a String, you need to add an = before the body, and make sure that the last statement in the body is indeed a String.

Additionally, the default case clause does not return anything. This does not work, because, again, getValue is declared to return a String. You need to either throw an exception in that case, or think of a default value to return (empty string?) or else use Options, like the other answer suggests.