0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

KotlinのNullable型の拡張関数

Posted at

Kotlinプログラマのみなさんにはお馴染みだと思いますが、次のコードはコンパイルエラーになります。

val nullableArray: Array<Int>? = null

// 次のコードはコンパイルエラー
println("nullableArray.isEmpty() is ${nullableArray.isEmpty()}")

Arrayの拡張関数、isEmpty

nullableArrayArray<Int>?型ですから、.での関数呼び出しはできません。コンパイルエラーになります。?.を使う必要があります。

さて、Kotlin 1.3から加わったメソッドに、isNullOrEmptyというメソッドがあります。

  • fun <T> Array<*>?.isNullOrEmpty(): Boolean
  • fun <T> Collection<T>?.isNullOrEmpty(): Boolean
  • fun <K, V> Map<out K, V>?.isNullOrEmpty(): Boolean

これは、

  • Array<*>?
  • Collection<T>?
  • Map<out K, V>?

の拡張関数です。

  • Array<*>
  • Collection<T>
  • Map<out K, V>

の拡張関数ではありません。Nullable型の拡張関数です。

Nullable型Array<*>?の拡張関数であるisNullOrEmptyisEmptyとの大きな違いがあります。

次のように、.でも呼び出すことができます。?.でなくても呼び出すことが可能です。

val nullArray: Array<Any>? = null

// 次のコードはコンパイルエラーにならない
println("nullArray.isNullOrEmpty() is ${nullArray.isNullOrEmpty()}") // true

このような拡張関数は、Kotlin 1.3に追加されたものもありますが、もともとKotlin 1.0からあったものもあります。例えば次のようなものです。

Nullable型でも、.で呼び出せる拡張関数がある。面白いですね。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?