在以下函数中,我传递了一个Option
。根据{{1}}是Option
还是Some
,我需要调用特定的API,但是其余的代码对于None
和{{1 }}。我不知道如何删除代码重复。我该如何以函数式编程风格重新编写代码?
Some
答案 0 :(得分:2)
def getRowsByPartitionKeyId(
id:I,
pagingStateOption:Option[PagingState]
): (Option[List[M]], Option[PagingState]) = {
val resultSet = session.execute(pagingStateOption match {
case Some(pagingState: PagingState) =>
whereClause.setFetchSize(1).setPagingState(pagingState)
case None =>
whereClause.setFetchSize(1)
})
val it = resultSet.iterator();//resultSet is an iterator
val newPagingState:PagingState = resultSet.getExecutionInfo.getPagingState
if (it.hasNext) {
val resultSetAsList:List[Row] = asScalaIterator(it).toList
val resultSetAsModelList = rowToModel(resultSetAsList.head)
Tuple2(Some(List(resultSetAsModelList)),Some(pagingState))
} else {
Tuple2(None, None)
}
}
答案 1 :(得分:0)
知道了。我忘记了Scala
中的所有内容都返回了一个值,甚至返回了match
,所以我可以做到这一点
val resultSet = pagingStateOption match {
case Some(pagingState: PagingState) => {
println("got paging state:" +pagingState)
session.execute(whereClause
.setFetchSize(1)
.setPagingState(pagingState)) //get one row from ResultSet. Cassandra might return more or less though
}
case None => {
session.execute(whereClause
.setFetchSize(1)) //get one row from ResultSet. Cassandra might return more or less though
}
}