yang
yang

Reputation: 508

how to write this function the scala way?

Consider this situation, I have a bunch of services that all need to check the input and handle errors.

val log = Logger("access")

def service1(){input=> 
    try{ 
        val id = input.split(",")(0).toInt
        val value = input.split(",")(1)
        //do something
    } catch {
        case e1: NumberFormatException => log.info("number format is wrong")
        case e2: ArrayIndexOutOfBoundsException=> log.info("not enough arguments")
    }
}

I want to write a method that handles this common part for every service. I could do it this way:

def common(input:String, log:Logger, action:(Int)=>String):String={
    try{ 
        val id = input.split(",")(0).toInt
        val value = input.split(",")(1)
        action(id)
    } catch {
        case e1: NumberFormatException => log.info("number format is wrong")
        case e2: ArrayIndexOutOfBoundsException=> log.info("not enough arguments")
    }
}

Then the service function looks like this:

def service1(){input=> common(input, log, id=>{
         //do something return a string
    })
}

Is there a way to skip the parameters in common so that it looks more elegant like map in collections?

common(id=>{ //... })

Upvotes: 0

Views: 93

Answers (1)

Andrzej Jozwik
Andrzej Jozwik

Reputation: 14659

import com.typesafe.scalalogging.StrictLogging


class MyService extends AbstractService {
  def service1(input: String): String = common(input) {
    id =>
      id.toString
  }

  def service2(input: String): String = common(input) {
    id =>
      id.toString.toLowerCase
  }
}

trait AbstractService extends StrictLogging {

  def common(input: String)(f: Int => String): String = {
    try {
      val id = input.split(",")(0).toInt
      f(id)
    } catch {
      case e1: NumberFormatException =>
        logger.error("number format is wrong",e1)
        "" //???
      case e2: ArrayIndexOutOfBoundsException =>
        logger.error("not enough arguments",e2)
        "" //???
    }
  }
}

If input is specific you have to put it as input. Otherwise define method def input:String in trait and provide implementation in service.

Upvotes: 1

Related Questions