2017年8月24日木曜日

Kotlin メモ : forEachIndexed

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/for-each-indexed.html


Java int pos = 1; for (Item item : items) { log(pos, item); pos++; } Kotlin 変換直後 var pos = 1 for (item in items) { log(pos, item) pos++ } forEachIndexed 使用 items.forEachIndexed { index, item -> log(index + 1, item)}


2017年8月22日火曜日

Kotlin メモ : mapNotNull

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-not-null.html


val list = (0 until adapter.count) .map { adapter.item(it) } .filterNotNull() .toList() mapNotNull 使用 val list = (0 until adapter.count) .mapNotNull { adapter.item(it) } .toList()

Kotlin メモ : until

https://kotlinlang.org/docs/reference/ranges.html
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.ranges/until.html


val list = (0..adapter.count - 1) .map { adapter.item(it) } .filterNotNull() .toList() until 使用 val list = (0 until adapter.count) .map { adapter.item(it) } .filterNotNull() .toList()

Kotlin メモ : filterNotNull

filterNotNull


Java final List<Item> list = new ArrayList<>(); for (int i = 0, count = adapter.getCount(); i < count; i++) { final Item item = adapter.getItem(i); if (item != null) { list.add(item); } } Kotlin 自動変換直後 val list = ArrayList<Item>() var i = 0 val count = adapter.count while (i < count) { val item = adapter.item(i) if (item != null) { list.add(item) } i++ } range, let 使用 val list = ArrayList<Item>() for(i in 0..adapter.count - 1) { adapter.item(i)?.let { list.add(it) } } map, filterNotNull 使用 val list = (0..adapter.count - 1) .map { adapter.item(it) } .filterNotNull() .toList()

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) }) }

2017年8月1日火曜日

Kotlin メモ : takeIf

Java public Hoge createFromParcel(Parcel source) { final int length = source.readInt(); final byte[] data; if (length > 0) { data = new byte[length]; source.readByteArray(data); } else { data = null; } return new Hoge(data); } Kotlin 変換直後 override fun createFromParcel(source: Parcel): Hoge { val length = source.readInt() val data: ByteArray? if (length > 0) { data = ByteArray(length) source.readByteArray(data) } else { data = null } return Hoge(data) } source.run {} を使う override fun createFromParcel(source: Parcel): Hoge = source.run { val length = readInt() val data: ByteArray? if (length > 0) { data = ByteArray(length) readByteArray(data) } else { data = null } Hoge(data) } also を使う override fun createFromParcel(source: Parcel): Hoge = source.run { val length = readInt() val data: ByteArray? if (length > 0) { data = ByteArray(length).also { readByteArray(it) } } else { data = null } Hoge(data) } if 式にしてみる override fun createFromParcel(source: Parcel): Hoge = source.run { val length = readInt() val data: ByteArray? = if (length > 0) { ByteArray(length).also { readByteArray(it) } } else { null } Hoge(data) } length に let を使う override fun createFromParcel(source: Parcel): Hoge = source.run { val length = readInt() val data: ByteArray? = if (length > 0) { length.let { ByteArray(it).also { readByteArray(it) } } } else { null } Hoge(data) } readInt() に takeIf を使う override fun createFromParcel(source: Parcel): Hoge = source.run { val data: ByteArray? = readInt() .takeIf { it > 0 } ?.let { ByteArray(it).also { readByteArray(it) } } Hoge(data) }


'},ClipboardSwf:null,Version:'1.5.1'}};dp.SyntaxHighlighter=dp.sh;dp.sh.Toolbar.Commands={ExpandSource:{label:'+ expand source',check:function(highlighter){return highlighter.collapse;},func:function(sender,highlighter) {sender.parentNode.removeChild(sender);highlighter.div.className=highlighter.div.className.replace('collapsed','');}},ViewSource:{label:'view plain',func:function(sender,highlighter) {var code=dp.sh.Utils.FixForBlogger(highlighter.originalCode).replace(/'+code+'');wnd.document.close();}},CopyToClipboard:{label:'copy to clipboard',check:function(){return window.clipboardData!=null||dp.sh.ClipboardSwf!=null;},func:function(sender,highlighter) {var code=dp.sh.Utils.FixForBlogger(highlighter.originalCode).replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');if(window.clipboardData) {window.clipboardData.setData('text',code);} else if(dp.sh.ClipboardSwf!=null) {var flashcopier=highlighter.flashCopier;if(flashcopier==null) {flashcopier=document.createElement('div');highlighter.flashCopier=flashcopier;highlighter.div.appendChild(flashcopier);} flashcopier.innerHTML='';} alert('The code is in your clipboard now');}},PrintSource:{label:'print',func:function(sender,highlighter) {var iframe=document.createElement('IFRAME');var doc=null;iframe.style.cssText='position:absolute;width:0px;height:0px;left:-500px;top:-500px;';document.body.appendChild(iframe);doc=iframe.contentWindow.document;dp.sh.Utils.CopyStyles(doc,window.document);doc.write('

'+highlighter.div.innerHTML+'

');doc.close();iframe.contentWindow.focus();iframe.contentWindow.print();alert('Printing...');document.body.removeChild(iframe);}},About:{label:'?',func:function(highlighter) {var wnd=window.open('','_blank','dialog,width=300,height=150,scrollbars=0');var doc=wnd.document;dp.sh.Utils.CopyStyles(doc,window.document);doc.write(dp.sh.Strings.AboutDialog.replace('{V}',dp.sh.Version));doc.close();wnd.focus();}}};dp.sh.Toolbar.Create=function(highlighter) {var div=document.createElement('DIV');div.className='tools';for(var name in dp.sh.Toolbar.Commands) {var cmd=dp.sh.Toolbar.Commands[name];if(cmd.check!=null&&!cmd.check(highlighter)) continue;div.innerHTML+=''+cmd.label+'';} return div;} dp.sh.Toolbar.Command=function(name,sender) {var n=sender;while(n!=null&&n.className.indexOf('dp-highlighter')==-1) n=n.parentNode;if(n!=null) dp.sh.Toolbar.Commands[name].func(sender,n.highlighter);} dp.sh.Utils.CopyStyles=function(destDoc,sourceDoc) {var links=sourceDoc.getElementsByTagName('link');for(var i=0;i');} dp.sh.Utils.FixForBlogger=function(str) {return(dp.sh.isBloggerMode==true)?str.replace(/
|<br\s*\/?>/gi,''):str;} dp.sh.RegexLib={MultiLineCComments:new RegExp('/\\*[\\s\\S]*?\\*/','gm'),SingleLineCComments:new RegExp('//.*$','gm'),SingleLinePerlComments:new RegExp('#.*$','gm'),DoubleQuotedString:new RegExp('"(?:\\.|(\\\\\\")|[^\\""\\n])*"','g'),SingleQuotedString:new RegExp("'(?:\\.|(\\\\\\')|[^\\''\\n])*'",'g')};dp.sh.Match=function(value,index,css) {this.value=value;this.index=index;this.length=value.length;this.css=css;} dp.sh.Highlighter=function() {this.noGutter=false;this.addControls=true;this.collapse=false;this.tabsToSpaces=true;this.wrapColumn=80;this.showColumns=true;} dp.sh.Highlighter.SortCallback=function(m1,m2) {if(m1.indexm2.index) return 1;else {if(m1.lengthm2.length) return 1;} return 0;} dp.sh.Highlighter.prototype.CreateElement=function(name) {var result=document.createElement(name);result.highlighter=this;return result;} dp.sh.Highlighter.prototype.GetMatches=function(regex,css) {var index=0;var match=null;while((match=regex.exec(this.code))!=null) this.matches[this.matches.length]=new dp.sh.Match(match[0],match.index,css);} dp.sh.Highlighter.prototype.AddBit=function(str,css) {if(str==null||str.length==0) return;var span=this.CreateElement('SPAN');str=str.replace(/ /g,' ');str=str.replace(/');if(css!=null) {if((/br/gi).test(str)) {var lines=str.split(' 
');for(var i=0;ic.index)&&(match.index/gi,'\n');var lines=html.split('\n');if(this.addControls==true) this.bar.appendChild(dp.sh.Toolbar.Create(this));if(this.showColumns) {var div=this.CreateElement('div');var columns=this.CreateElement('div');var showEvery=10;var i=1;while(i<=150) {if(i%showEvery==0) {div.innerHTML+=i;i+=(i+'').length;} else {div.innerHTML+='·';i++;}} columns.className='columns';columns.appendChild(div);this.bar.appendChild(columns);} for(var i=0,lineIndex=this.firstLine;i0;i++) {if(Trim(lines[i]).length==0) continue;var matches=regex.exec(lines[i]);if(matches!=null&&matches.length>0) min=Math.min(matches[0].length,min);} if(min>0) for(var i=0;i

Blogger Syntax Highliter

Version: {V}

http://www.dreamprojections.com/syntaxhighlighter

©2004-2007 Alex Gorbatchev.

'},ClipboardSwf:null,Version:'1.5.1'}};dp.SyntaxHighlighter=dp.sh;dp.sh.Toolbar.Commands={ExpandSource:{label:'+ expand source',check:function(highlighter){return highlighter.collapse;},func:function(sender,highlighter) {sender.parentNode.removeChild(sender);highlighter.div.className=highlighter.div.className.replace('collapsed','');}},ViewSource:{label:'view plain',func:function(sender,highlighter) {var code=dp.sh.Utils.FixForBlogger(highlighter.originalCode).replace(/'+code+'');wnd.document.close();}},CopyToClipboard:{label:'copy to clipboard',check:function(){return window.clipboardData!=null||dp.sh.ClipboardSwf!=null;},func:function(sender,highlighter) {var code=dp.sh.Utils.FixForBlogger(highlighter.originalCode).replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');if(window.clipboardData) {window.clipboardData.setData('text',code);} else if(dp.sh.ClipboardSwf!=null) {var flashcopier=highlighter.flashCopier;if(flashcopier==null) {flashcopier=document.createElement('div');highlighter.flashCopier=flashcopier;highlighter.div.appendChild(flashcopier);} flashcopier.innerHTML='';} alert('The code is in your clipboard now');}},PrintSource:{label:'print',func:function(sender,highlighter) {var iframe=document.createElement('IFRAME');var doc=null;iframe.style.cssText='position:absolute;width:0px;height:0px;left:-500px;top:-500px;';document.body.appendChild(iframe);doc=iframe.contentWindow.document;dp.sh.Utils.CopyStyles(doc,window.document);doc.write('

'+highlighter.div.innerHTML+'

');doc.close();iframe.contentWindow.focus();iframe.contentWindow.print();alert('Printing...');document.body.removeChild(iframe);}},About:{label:'?',func:function(highlighter) {var wnd=window.open('','_blank','dialog,width=300,height=150,scrollbars=0');var doc=wnd.document;dp.sh.Utils.CopyStyles(doc,window.document);doc.write(dp.sh.Strings.AboutDialog.replace('{V}',dp.sh.Version));doc.close();wnd.focus();}}};dp.sh.Toolbar.Create=function(highlighter) {var div=document.createElement('DIV');div.className='tools';for(var name in dp.sh.Toolbar.Commands) {var cmd=dp.sh.Toolbar.Commands[name];if(cmd.check!=null&&!cmd.check(highlighter)) continue;div.innerHTML+=''+cmd.label+'';} return div;} dp.sh.Toolbar.Command=function(name,sender) {var n=sender;while(n!=null&&n.className.indexOf('dp-highlighter')==-1) n=n.parentNode;if(n!=null) dp.sh.Toolbar.Commands[name].func(sender,n.highlighter);} dp.sh.Utils.CopyStyles=function(destDoc,sourceDoc) {var links=sourceDoc.getElementsByTagName('link');for(var i=0;i');} dp.sh.Utils.FixForBlogger=function(str) {return(dp.sh.isBloggerMode==true)?str.replace(/
|<br\s*\/?>/gi,'\n'):str;} dp.sh.RegexLib={MultiLineCComments:new RegExp('/\\*[\\s\\S]*?\\*/','gm'),SingleLineCComments:new RegExp('//.*$','gm'),SingleLinePerlComments:new RegExp('#.*$','gm'),DoubleQuotedString:new RegExp('"(?:\\.|(\\\\\\")|[^\\""\\n])*"','g'),SingleQuotedString:new RegExp("'(?:\\.|(\\\\\\')|[^\\''\\n])*'",'g')};dp.sh.Match=function(value,index,css) {this.value=value;this.index=index;this.length=value.length;this.css=css;} dp.sh.Highlighter=function() {this.noGutter=false;this.addControls=true;this.collapse=false;this.tabsToSpaces=true;this.wrapColumn=80;this.showColumns=true;} dp.sh.Highlighter.SortCallback=function(m1,m2) {if(m1.indexm2.index) return 1;else {if(m1.lengthm2.length) return 1;} return 0;} dp.sh.Highlighter.prototype.CreateElement=function(name) {var result=document.createElement(name);result.highlighter=this;return result;} dp.sh.Highlighter.prototype.GetMatches=function(regex,css) {var index=0;var match=null;while((match=regex.exec(this.code))!=null) this.matches[this.matches.length]=new dp.sh.Match(match[0],match.index,css);} dp.sh.Highlighter.prototype.AddBit=function(str,css) {if(str==null||str.length==0) return;var span=this.CreateElement('SPAN');str=str.replace(/ /g,' ');str=str.replace(/');if(css!=null) {if((/br/gi).test(str)) {var lines=str.split(' 
');for(var i=0;ic.index)&&(match.index/gi,'\n');var lines=html.split('\n');if(this.addControls==true) this.bar.appendChild(dp.sh.Toolbar.Create(this));if(this.showColumns) {var div=this.CreateElement('div');var columns=this.CreateElement('div');var showEvery=10;var i=1;while(i<=150) {if(i%showEvery==0) {div.innerHTML+=i;i+=(i+'').length;} else {div.innerHTML+='·';i++;}} columns.className='columns';columns.appendChild(div);this.bar.appendChild(columns);} for(var i=0,lineIndex=this.firstLine;i0;i++) {if(Trim(lines[i]).length==0) continue;var matches=regex.exec(lines[i]);if(matches!=null&&matches.length>0) min=Math.min(matches[0].length,min);} if(min>0) for(var i=0;i

ページビューの合計