Butterknife: How to optionally bind nullable views in Kotlin

Created on 20 Oct 2016  路  3Comments  路  Source: JakeWharton/butterknife

I'm trying to bind a nullable (optional) view in kotlin (not using KotterKnife), and I'm getting this error.

@BindView fields must not be private or static

What's the workaround? Tried the below with no luck (same error)

@field:[BindView(R.id.home_toolbar) Nullable] var toolbar: Toolbar? = null

Most helpful comment

That's a property whose backing field is private. Add @JvmField to generate a public field instead.

All 3 comments

That's a property whose backing field is private. Add @JvmField to generate a public field instead.

Thanks Jake, coming through in the clutch.

Example of fix below.

@BindView(R.id.home_toolbar) @Nullable @JvmField var toolbar: Toolbar? = null

The @Nullable annotation is not required because ButterKnife will assume the binding is optional if it finds any annotation named "Nullable" on the field. An optional field in Kotlin seen in java as a field with the org.jetbrains.annotations.Nullable annotation applied, which ButterKnife understands. Thus, you can write the binding as:

@BindView(R.id.home_toolbar) @JvmField var toolbar: Toolbar? = null
Was this page helpful?
0 / 5 - 0 ratings