tmp123 tmp123 - 6 months ago 24
Scala Question

Scala: Function with dynamic contract as argument

I have the following enum.

object Smth extends Enumeration {
class Value(name: String, func: (String, Int) => Boolean) extends super.Val(name)

private def opA(index: Int) : Boolean ={
index > 0
private def opB(x: String, index: Int) : Boolean ={
index > 0 && x.length > 0

val x = new Value("X", opA) // type mismatch error for opA
val y = new Value("Y", opB)

Enum constructor takes as an argument a function, of type
(String, Int) => Boolean
. Is it possible to create enum constructor in such a way that it will accept functions with 2 distinct contracts, for example:

(String, Int) => Boolean
(Int) => Boolean

I am trying to avoid using default value for argument, in function definition.

This is how I would like to use it.

if(Smth.x.func(0)) { do smth }
else if(Smth.y.func("str", 0)) { do smthElse }


If you just want default value you can do this:

class Value(val name: String, val func: (String, Int) => Boolean) extends super.Val(name) { 
    def apply(name: String, func: (Int) => Boolean): Value = 
        new Value(name, (x -> func("default value", x)))