Photo by Walkator on Unsplash

Efficiently Inflating ViewBindings with a Generic and Reified Kotlin Function

Miny Zeether

--

In this comparison, we will look at two different ways to inflate ViewBindings in Kotlin. The first solution is a non-generic function that requires modification every time a different type of ViewBinding is used. The second solution is a generic function that uses Kotlin’s reified generics, allowing it to be used with any type that implements ViewBinding without modification. We will analyze both solutions and compare their performance and ease of use.

Solution 1

This the default behaviour. Normally you use it every day i.e. while inflating view in RecyclerViewAdapter. It does not use reified generics and is not generic, meaning that you have to change the code every time you want to use a different type.

fun ViewBinding.inflate(parent): T {
return T.inflate(LayoutInflater.from(parent.context), parent, false)
}

Usage:

val binding = MyItem1Binding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)

Solution 2

This solution is generic and uses reified generics, meaning that you can use it with any type that implements ViewBinding without having to modify the code. Yay!

inline fun <reified T : ViewBinding> inflateViewBinding(parent: ViewGroup): T {
val layoutInflater = LayoutInflater.from(parent.context)
return T::class.java.getMethod(
"inflate",
LayoutInflater::class.java,
ViewGroup::class.java,
Boolean::class.javaPrimitiveType
).invoke(null, layoutInflater, parent, false) as T
}

Usage:

val binding = inflateViewBinding<MyItemBinding>(parent)

Summary and performance check:

As you can see, the first solution is a non-generic function that requires modification every time a different type of ViewBinding is used. This means that if you want to inflate a different ViewBinding, you have to go into the code and change it. On the other hand, the second solution is a generic function that uses Kotlin’s reified generics, allowing it to be used with any type that implements ViewBinding without modification. This means that you can inflate any ViewBinding without having to change the code. The second solution is more versatile and convenient to use.

So, if someone asked me:

How much time would I save if I used to use second solution for one year?

I would say that it might be difficult to estimate the exact amount of time because it would depends on various factors … but! It is likely that you would save a significant amount of time over the course of a year, as you would not have to make changes to the code every time you inflate a different ViewBinding. So, please, select the second solution! :-)

--

--

No responses yet