簡體   English   中英

是否可以在Scala中裝飾方法?

[英]Is it possible to decorate methods in scala?

所以,我有一個帶有方法的對象,像這樣:

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
}

例如,我想用相同的代碼處理所有方法中的錯誤:

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

Scala中有沒有辦法處理這樣的錯誤並且沒有代碼重復?

您可以創建一個私有函數來處理錯誤:

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

您可以這樣調用tryUnsafe

tryUnsafe {
  // code that eventually return a String
}

編輯:添加詳細信息以解決第一個評論。

您可以在函數中使用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
  }
}

在回答您的問題時,我假設* domethodcreateObjectdeleteObject等的占位符* doSomeOtherMethod對於所有domethod都是domethod的,而不是每個操作一個特定的,如果不是這種情況,除了可以使用g參數f調用您的if語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM