0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

文字列の先頭1文字を安全に取る(take(n) を使おう)

0
Posted at

問題点

item.name.first() は空文字でクラッシュするという点です。

  text = item.name.first().toString()        

このように実装するとnameが空文字 のときNoSuchElementExceptionがスローされます。

.first() について調べてみたのですが、String.first() は Iterable の拡張関数で、要素がゼロ(= 空文字)のとき例外を投げます。

修正

text = item.name.take(1)   

こちらを使うようにします。
これなら先頭 n 文字を返すだけなので、文字数が足りなくても安全です。

同じように書けるもので、

  text = firstOrNull()?.toString() ?: ""

 もあるのですが、.take(n)で書いた方が簡潔書けるのでいいと思いました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?