- 投稿日:2019-05-27T21:14:11+09:00
kotlinでtry-with-resourcesするやつ
いきなり結論
残念ながらkotlinにはtry-with-resourcesそのものはないです。
その代わり、同等のfunction(厳密にはextension function: 拡張関数)としてuseがあります。javatry (OutputStream ost = Files.newOutputStream(path)) { FileCopyUtils.copy(inst, ost); } catch (Exception e) { e.printStackTrace(); }これが↓
kotlintry { Files.newOutputStream(path).use { ost -> FileCopyUtils.copy(inst, ost) } } catch (e: Exception) { e.printStackTrace() }こうなります。
個人的には
useの中身が1行であればFiles.newOutputStream(path).use { ost -> FileCopyUtils.copy(inst, ost) }みたいに改行せずに書くことが多いです。
kotlinはjavaに比べてスッキリと書けるのところが好きなので。複数resourceの場合
複数のresourceを使いたい場合は
useをchainできます。kotlintry { Files.newOutputStream(path).use { ost -> Files.newInputStream(path).use { inst -> FileCopyUtils.copy(inst, ost) } } } catch (e: Exception) { e.printStackTrace() }あまりchainしすぎるとネストが深くなるのが玉に瑕。
参考
- Try-with-resources in Kotlin | Baeldung
- kotlin/Closeable.kt at master · JetBrains/kotlin
- 参考っていうか
useの実装。気になったら一度目を通しても良いかも
- 投稿日:2019-05-27T13:58:23+09:00
kotlinの'@'ラベルを使っていつでもreturnする
val callback = { // なにか ... } ... callback?.invoke()kotlinは
{}で囲まれたコードは、ラムダ式になるのでこんなこともできます。
しかし、、、val callback = { if (someValue == 100) return // <- エラー ... } ... callback?.invoke()ラムダ式の中で
returnするとエラーになってしまいます。
メソッドにラムダ式を使うときは@メソッド名をつけると問題なくreturnできるのですが、
上のコードの場合は@のあとに付ける名前が無いのでできません。list.forEach { if (it == 10) return@forEach }こういうときはラベルを付ければいいよという話。
val callback = mark@{ if (someValue == 100) return@mark ... } ... callback?.invoke()
markっていうのは適当に付けたもので実際は何でもいい。
@の位置がラベル付けとreturnで違うのがモヤモヤするけど、
便利です。
- 投稿日:2019-05-27T11:32:46+09:00
【Android】Databinding × レイアウトファイル(XML)で文字列を結合しつつ表示させる
databindingを使って、更に文字列を結合してtextViewに表示したかっただけなんだ...
既知かもしれんけど、結構ハマったので忘備録。。。はじめに書いてたレイアウトファイル
activity_sample.xmlandroid:text="@{sampleViewModel.birthdayYear + '年' + sampleViewModel.birthdayMonth + '月' + sampleViewModel.birthdayDate + '日'}"めっちゃエラー出た。スタックトレースは割愛ちゃん。
「構文エラー:期待してた入力じゃないです(意訳)」って言われるe: [kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data binding errors. ****/ data binding error ****msg:Syntax error: extraneous input '?' expecting {'(', '+', '-', '~', '!', 'boolean', 'char', 'byte', 'short', 'int', 'long', 'float', 'double', VoidLiteral, IntegerLiteral, FloatingPointLiteral, BooleanLiteral, CharacterLiteral, SingleQuoteString, DoubleQuoteString, 'null', Identifier, ResourceReference} file:/Android/Sample/app/src/main/res/layout/activity_sample.xml loc:158:40 - 158:187 ****\ data binding error ****正解だったレイアウトファイル
activity_sample.xmlandroid:text='@{sampleViewModel.birthdayYear + @string/common_year + sampleViewModel.birthdayMonth + @string/common_month + sampleViewModel..birthdayDate + @string/common_day}'いつもお世話になってるstackoverflowからこの記事を発見。
databindingのバグじゃない?って書いてあるけどほんとかなー。AndroidStudioの補完くん優秀だからだいたい
@stringの候補出してくれるけど、
この箇所に限っては補完候補全然出てこないので不安になる。タイポ注意ネ