有沒有辦法在scala對象中隱式添加方法?隱式添加對象方法
UPD: 例如,未過濾的Scala庫具有單獨的對象Body
其中包含方法Body.string(req: HttpRequest)
Body.bytes(req: HttpRequest)
和用於讀的身體從http請求。所以,我想在我的域對象中讀取正文,如Body.cars(req:HttpRequest)
。
有沒有辦法在scala對象中隱式添加方法?隱式添加對象方法
UPD: 例如,未過濾的Scala庫具有單獨的對象Body
其中包含方法Body.string(req: HttpRequest)
Body.bytes(req: HttpRequest)
和用於讀的身體從http請求。所以,我想在我的域對象中讀取正文,如Body.cars(req:HttpRequest)
。
import scala.language.implicitConversions
object ObjA
object ObjB {
def x = 1
}
object Main {
implicit def fromObjA(objA: ObjA.type) = ObjB
def main(args: Array[String]): Unit = {
println(ObjA.x)
}
}
你是什麼意思隱式添加方法?這段代碼剪斷回答你的問題:
implicit def toFunkyString(s: String) = new {
def reverseUpper = s.reverse.toUpperCase
}
"Foo".reverseUpper //yields 'OOF'
toFunkyString("Foo").reverseUpper //explicit invocation
'「Foo」'是一個類實例,我的意思是在單例對象中添加方法,如'Math.myMethod(1)'。這一切都一樣嗎? – KkZz
請更好地解釋你想要什麼。 –