我们有一个特征,除其他外,还包含execute[T <: Record](Seq[(Session) => T]): Seq[T]
方法,其中Record
是我们从数据库中检索的所有特征的超级特征
trait DbTrait {
val threadCount: Int
val db: Database
protected def getGroupSize(size: Int, threadCount: Int) {
(size / threadCount) + if(size % threadCount == 0) 0 else 1
}
def execute[T <: Record](funs: Seq[(Session) => T]): Seq[T]
}
trait DbTraitSingle extends DbTrait {
val threadCount = 1
def execute[T <: Record](funs: Seq[(Session) => T]): Seq[T] =
db.withSession{session: Session => funs.map(f => f(session))}
}
trait DbTraitMulti extends DbTrait {
val threadCount = 4
def execute[T <: Record](funs: Seq[(Session) => T): Seq[T] =
funs.grouped(getGroupSize(funs.size, threadCount)).map(funs => Future {
db.withSession{session: Session => funs.map(f => f(session))}
}.toList.flatten
}
等等。理想情况下,我们希望能够创建类似
def executePoly2[T1 <: Record, T2 <: Record]
(tuple: Tuple2[(Session) => T1, (Session) => T2]): Tuple2[T1, T2]
对于任意元组(即executePoly3、executePoly4等),但有两个问题:
- 有没有办法减少这里的样板文件数量,或者我们会被困在创建 22 个不同的方法签名中?
- 是否有一种类型安全的方法来分割类似于
seq.grouped
方法调用,或者我们是否陷入了所有不同的特殊情况threadCount
值(目前不超过 4)?
您可以使用 Miles Sabin 的 Shapeless 库来获得非常易于使用的东西。看看他们可以用Tuple https://github.com/milessabin/shapeless/wiki/Feature-overview%3a-shapeless-2.0.0#hlist-style-operations-on-standard-scala-tuples。特别是对数量进行抽象。
import syntax.std.tuple._
import poly._
var myProducedTuple = myTuple map (_(session))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)