2017年8月16日水曜日

Kotlin メモ : indexOfFirst

indexOfFirst

predicate にマッチする最初の位置の index を返す。マッチするものが無い場合は -1 を返す。


Java
  1. @Override  
  2. public int getSectionForPosition(int position) {  
  3.     final Object[] sections = getSections();  
  4.     if (sections == null) {  
  5.         return 0;  
  6.     }  
  7.     int section = 0;  
  8.     for (int i = 0; i < sections.length; i++) {  
  9.         final MonthSection ms = (MonthSection) sections[i];  
  10.         if (ms.position > position) {  
  11.             return section;  
  12.         }  
  13.         section = i;  
  14.     }  
  15.     return section;  
  16. }  
Kotlin
  1. override fun getSectionForPosition(position: Int): Int {  
  2.     val sections = getSections() ?: return 0  
  3.     return sections.indexOfFirst { it.position > position }  
  4.             .let {  
  5.                 when {  
  6.                     it > 0 -> it - 1  
  7.                     it == 0 -> 0  
  8.                     else -> sections.lastIndex  
  9.                 }  
  10.             }  
  11. }  

0 件のコメント:

コメントを投稿