![](/img/trans.png)
[英]using duck typing to create mixins in Scala, can i decorate existing methods in a class that has no 'knowledge' of the mixin trait?
[英]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
}
}
在回答您的問題時,我假設* domethod
是createObject
, deleteObject
等的占位符* doSomeOtherMethod
對於所有domethod
都是domethod
的,而不是每個操作一個特定的,如果不是這種情況,除了可以使用g
參數f
調用您的if
語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.