我有几个类似的功能:
import reactivemongo.play.json.collection.JSONCollection
def quotesFuture: Future[JSONCollection] = database.map(_.collection[JSONCollection]("quotes"))
1: def getByAuthor(author: String) = Action.async {
2: quotesFuture.flatMap{ quotes =>
3: quotes
4: .find(obj("author" -> author))
5: .cursor[JsObject](ReadPreference.primary)
6: .collect[List](maxQuotes)
7: .map(q => Ok(Json.toJson(q)))
8: }
9: }
10:
11: def search(term: String) = Action.async {
12: quotesFuture.flatMap{ quotes =>
13: quotes
14: .find(obj("$text" -> obj("$search" -> term)), textScore)
15: .sort(textScore)
16: .cursor[JsObject](ReadPreference.primary)
17: .collect[List](maxQuotes)
18: .map(q => Ok(Json.toJson(q)))
19: }
20: }但是有很多重复;唯一改变的是查找和排序,所以我想重构如下:
100: def getByAuthor(author: String) = getList { quotes =>
101: quotes
102: .find(obj("author" -> author))
103: }
104:
105: def search(term: String) = getList { quotes =>
106: quotes
107: .find(obj("$text" -> obj("$search" -> term)), textScore)
108: .sort(textScore)
109: }
110:
111: def getList(query: (JSONCollection) => ???) = Action.async {
112: quotesFuture.flatMap{ quotes =>
113: query(quotes)
114: .cursor[JsObject](ReadPreference.primary)
115: .collect[List](maxQuotes)
116: .map(q => Ok(Json.toJson(q)))
117: }
118: }问题是,第111行的??? 应该是什么?
当要求IntelliJ从第14-15行提取方法时,它会创建以下内容
def tempdef(term: String, quotes: JSONCollection): GenericQueryBuilder[quotes.pack.type]#Self = {
quotes
.find(obj("$text" -> obj("$search" -> term)), textScore)
.sort(textScore)
}IntelliJ提出的结果类型非常可怕。因此,第111行中的???应该是GenericQueryBuilder[quotes.pack.type]#Self,但它取决于变量quotes。我应该用什么来代替???来完成这个任务呢?
使用IntelliJ,我看到quotes.pack指的是:
case class JSONCollection(...) {...
val pack = JSONSerializationPack
}我尝试用JSONSerializationPack.type替换第111行中的JSONSerializationPack.type,它编译并工作。
然而,查看JSONCollection的实现细节是欺骗,如果JSONCollection的实现发生变化,这可能会停止工作。
那么,第111行的???应该是什么呢?
否则,在本例中,您是否看到了一种更简单的删除代码复制的方法?
发布于 2016-08-16 17:14:33
我建议您的getByAuthor和search返回一个Cursor[JsObject],它允许它们具有不同的ReadPreference,并使用非依赖类型(与查询生成器相反,查询生成器依赖于集合的底层序列化包,这是IDE所不理解的)。
导入reactivemongo.api.Cursor
def getByAuthor(author: String): Cursor[JsObject] = ???
def search(term: String): Cursor[JsObject] = ???
def getList(cursor: JSONCollection => Cursor[JsObject] = Action.async {
quotesFuture.flatMap { quotes =>
val c: Cursor[JsObject] = cursor(quotes)
???
}https://stackoverflow.com/questions/38978615
复制相似问题