Wrapping generic function calls with one method

I have something like this:

...
case BooleanType => 
  try {
    reader.getBooleanValue()
  } catch {
    case e: IllegalStateException => throwMyException()
  }
case IntegerType => 
  try {
    reader.getIntValue()
  } catch {
    case e: IllegalStateException => throwMyException()
  }
...etc

but that's a lot of duplicate code. There must be a way to do something like:

case BooleanType => tryGetReaderSafely(reader.getBooleanValue())
case IntegerType => tryGetReaderSafely(reader.getIntValue())
..etc

where the method I'm curious about is

def tryGetReaderSafely(reader: Reader): Any = {
  try {
    reader.getType // how do I do the correct call here?
  } catch {
    case e: IllegalStateException => throwMyException()
  }
}

The problem is that I'm passing the function result and not the function itself into the call -- I know you can use callbacks but I still am not sure how to use the callback to call the correct reader.getType methods

Upvotes: 0

Views: 46

Answers (1)

Jean Logeart
Jean Logeart

Reputation: 53829

Try:

def tryGetReaderSafely[T](reader: Reader, f: Reader => T): T =
  try {
    f(reader)
  } catch {
    case e: IllegalStateException => throwMyException()
  }

Usage:

case BooleanType => tryGetReaderSafely(reader, _.getBooleanValue)
case IntegerType => tryGetReaderSafely(reader, _.getIntValue)

Upvotes: 1

Related Questions