i'd like to ask for your help about beautifying client code.
Let's say I have some basic methods for MongoDB retrieval:
def find(dbo:DBObject):MongoCursor =
mongoColl.find(dbo)
def Sort(cursor: MongoCursor, sortFun: DBObject): MongoCursor =
cursor.sort(sortFun)
def Limit(cursor: MongoCursor, number: Int): MongoCursor = cursor.limit(number)
def Offset(cursor: MongoCursor, number: Int): MongoCursor = cursor.skip(number)
def toList(cursor: MongoCursor): List[A] =
cursor map (readConverter(_)) toList
and i wanna chain them together in different ways (let say i wanna perform some limited searchs, some sorted searchs, just like a decorator basically). how would you do it?
Thanks for your help.
You could try to use an implicit value class to enrich the MongoCursor
:
object ImplicitClassContainer {
implicit class RichMongoCursor(val mc: MongoCursor) extends AnyVal {
def sort(sortFun: DBObject): MongoCursor = mc.sort(sortFun)
def limit(number: Int): MongoCursor = mc.limit(number)
def offset(number: Int): MongoCursor = mc.skip(number)
}
}
to be used like this
import ImplicitClassContainer._
def x(mc: MongoCursor): MongoCursor = {
mc.offset(25).limit(25)
}
Basically it's the same pattern which is used to add functionality to Array
: You get additional functions in "flow style", but it's still a MongoCursor
. As it is an implicit value class , no additional instance of an object is created at run-time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.