是否可以在scala中装饰方法?

Sto*_*ran 2 scala scala-2.11

所以,我有一个对象,有方法,类似的东西:

object Connector {

  def createObject (id : Long, x : Double, y : Double, name : String, objtype : Int, layer : String) : String  = {
    //some code
  }

  def deleteObject (id : Long) : String  = {
    //some code
  }

  def findObject (name : String) : String  = {
    //some code
  }

  //some other methods
}
Run Code Online (Sandbox Code Playgroud)

例如,我想在所有方法中处理错误,使用相同的代码:

var res = domethod(methodParams)
if (res.indexOf("Error") > 0){
  doSomeOtherMethod() //that can fix error
  res = domethod(methodParams) //with same params
}
return res
Run Code Online (Sandbox Code Playgroud)

在Scala中有没有办法处理这样的错误,没有代码重复?

vpt*_*ron 6

您可以创建一个私有函数来处理错误:

private def tryUnsafe(f: => String): String = {
  var res = f()
  if (res.indexOf("Error") > 0){
    doSomeOtherMethod() //that can fix error
    res = f()
  }
  return res
}
Run Code Online (Sandbox Code Playgroud)

你可以tryUnsafe像这样打电话:

tryUnsafe {
  // code that eventually return a String
}
Run Code Online (Sandbox Code Playgroud)

编辑:添加详细信息以解决第一条评论.

你可以tryUnsafe在你的函数中使用这样的:

def createObject (id : Long, x : Double, y : Double, name : String, objtype : Int, layer : String) : String  = {
  tryUnsafe {
    // the code to create an object, that returns a String
  }
}
Run Code Online (Sandbox Code Playgroud)

在回答你的问题,我认为* domethod是一个占位符createObject,deleteObject等* doSomeOtherMethod对所有相同domethod秒且不每操作一个特定的一个,如果不是的话,你可以采取一个g参数,除了f在你的调用if语句.