Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does 'by' differ from '=' in Kotlin?

What is the functional difference between the two lines of code:

private val binding = viewBinding(Fragment::bind)
private val binding by viewBinding(Fragment::bind)

I tried reading this stack overflow post on what is the by keyword used for in Kotlin but, it says that it replaces the getter and setter functions to the expression following the by keyword so why have it at all if you can just use = instead, to set the object to a particular value?

like image 921
Trake Vital Avatar asked Sep 15 '25 21:09

Trake Vital


1 Answers

'=' means binding is assigned to the value of viewBinding() method immediately. It doesn't require any other calls.

'by' is used to set a delegation. 'by' act as a getter of the binding to the viewBinding() method result. What is does actually, binding won't be result of viewBinding() until binding itself is not accessed. By using 'by' you can trigger a lazy initialization.

more at Delegated properties

like image 91
K M Rejowan Ahmmed Avatar answered Sep 17 '25 12:09

K M Rejowan Ahmmed