最近,我在代碼中發現了幾個我第一次收集某些解決方案的地方,然後僅在解決方案是唯一的時才繼續處理它們(解決方案集合僅包含一個元素)。以下代碼是嘗試以更多功能的方式解決此問題。將「pimp my Iterable」擴展爲選項
implicit class GetOnlyOne[A](val coll: Iterable[A]) {
def getonlyone = {
if (coll.isEmpty) None
else if (coll.tail.isEmpty) coll.headOption
else None
}
}
功能可以像使用:
Seq(1).getonlyone
Seq(1,2).getonlyone
Set(1).getonlyone
什麼目前不工作是:
Some(1).getonlyone
能的功能加以改進,以接受Option
以及時,除了與Iterable
小號,也許有看法界限?