lundi 7 octobre 2019

Is it possible to build type-driven function lookup tables in Scala?

I know how to do this in Lisp / Scheme / Racket, but not in Scala.

// inputType  derives from In  and could be of subtype In1, In2, In3, ...
// outputType derives from Out and could be of subtype Out1, Out2, Out3, ...

def invokeTheRightFunction
  (functionName: Mystery1, inputData: [subtype of In], outputType: Mystery2): Mystery3 =
{
  val lookupTable =
    List( Mystery4(functionName1, inputType1, outputType1),
          Mystery4(functionName2, inputType2, outputType2),
          ...
          Mystery4(functionNameN, inputTypeN, outputTypeN) )
  ...Mystery5...
}

Based on values of functionName, inputType, and outputType, given inputData that is of a particular subtype of In, is it possible to use build a lookupTable so that the proper function is called with the inputData, and the returned value from the function with the lookupTable has the correct subtype of Out?

If you're wondering why I don't just use match/case, it's because I want there to be some generic [database handling] code in a library, but the code that uses the library will know what all the types should be going in and coming out.

The code for In, Out, and the "Mysteries" would be in the library.

Subtypes of In and Out and lookupTable would be in the code that uses the library.

To make this a little more concrete, let's say I have [database] stored procedures A, B, C. I currently put the inputs to those stored procedures in case classes called ArgsA, ArgsB, ArgsC. I get the answers back as a sequence of RowA, RowB, RowC. I want all or most of the error handling to happen in the library.

The code I have now has some duplication of type-specification, and I'm trying to consolidate specification of types to a single lookup table to reduce the chance of error.





Aucun commentaire:

Enregistrer un commentaire