2017年8月16日水曜日

Kotlin メモ : indexOfFirst

indexOfFirst

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


Java @Override public int getSectionForPosition(int position) { final Object[] sections = getSections(); if (sections == null) { return 0; } int section = 0; for (int i = 0; i < sections.length; i++) { final MonthSection ms = (MonthSection) sections[i]; if (ms.position > position) { return section; } section = i; } return section; } Kotlin override fun getSectionForPosition(position: Int): Int { val sections = getSections() ?: return 0 return sections.indexOfFirst { it.position > position } .let { when { it > 0 -> it - 1 it == 0 -> 0 else -> sections.lastIndex } } }

2017年8月10日木曜日

Kotlin メモ : ArrayAdapter

Java class MyAdapter extends ArrayAdapter<MyData> { private final LayoutInflater inflater; MyAdapter(Context context, List<MyData> objects) { super(context, 0, objects); inflater = LayoutInflater.from(context); } ... @NonNull @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { final MyViewHolder holder; if (convertView == null) { holder = MyViewHolder.create(inflater, parent); convertView = holder.view; convertView.setTag(holder); } else { holder = (MyViewHolder) convertView.getTag(); } final MyData data = getItem(position); assert data != null; holder.bind(data); return convertView; } } Kotlin class MyAdapter(context: Context, objects: List<MyData>) : ArrayAdapter<MyData>(context, 0, objects) { private val inflater = LayoutInflater.from(context) ... override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view: View = convertView ?: MyViewHolder.create(inflater, parent) .also { it.view.tag = it } .view getItem(position)?.let { (view.tag as MyViewHolder).bind(it) } return view } }

2017年8月3日木曜日

Kotlin メモ : joinToString

kotlin-stdlib / kotlin.collections / joinToString

Java /** * 00 11 22 33 44 55 66 77 */ @NonNull public String expression(byte[] bytes) { final StringBuilder sb = new StringBuilder(); boolean firstTime = true; for (byte each : bytes) { if (firstTime) { firstTime = false; } else { sb.append(" "); } sb.append(hex(each)); } return sb.toString(); } Java その2 /** * 00 11 22 33 44 55 66 77 */ @NonNull public String expression(byte[] bytes) { final List<String> tokens = new ArrayList<>(); for (byte each : bytes) { tokens.add(hex(each)); } return TextUtils.join(" ", tokens); } Kotlin /** * 00 11 22 33 44 55 66 77 */ fun expression(bytes : ByteArray): String { return bytes.joinToString(separator = " ", transform = { hex(it) }) }