28
20

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でParameter specified as non-null is null

Posted at

Kotlin素人すぎてハマったのでメモ。
Kotlinはnullに対して厳密な世界なので関数を記述するときには、きちんと継承元のjava関数のNullableを気にしなくてはならない。

誤った記述

例えば、FragmentのonCreateView.

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle) : View {
}

と書くと、コンパイルは通るのだけれど、実行時にIllegalArgumentExceptionが発生する。

Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter savedInstanceState

これはsavedInstanceStateにnullが渡ってきて、kotlinのoptional定義と矛盾してしまったため。

正しい記述

java側の定義をみてみる。

@Nullable
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
}

が元の定義なので、

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) : View? {
}

で継承しなくてはならない。

28
20
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
28
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?