gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:43:18 26 4
gpt4 key购买 nike

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

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)函数来处理您的错误:

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 都是相同的,而不是每个操作特定的一个,如果不是这种情况,您可以采用 g 参数除了 f 之外,还可以调用您的 if 语句。

关于scala - 是否可以在 Scala 中装饰方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29349149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com