Posts

Showing posts from December, 2021

Companion Object in Kotlin

Image
Overview If you want to write some functions or properties of a class and you want to use it without creating an instance of that class, then you should write these functions and properties in a companion object. Companion object is similar to Singleton object. All the functions and properties in a companion object are static.  Object vs Companion Object Object can be used when you don't want to write some static functions or properties inside a class. Companion object can be used when you want to write some functions or properties of a class as static. Do's and Dont's You can give a name to a companion object but it's of no use.  class ToBeCalled { companion object Test { var someInteger : Int = 10 fun callMe () = println ( "You are calling me :)" ) } } fun main (args: Array<String>) { print (ToBeCalled. someInteger ) } Companion object can be created outside a class. Reference https://blog.mindorks.com/companion-object-i

Difference between lateinit and lazy in Kotlin

Image
lateinit lateinit is used when you just want to declare a variable but don't want to initialize it. But you make sure that you are going to initialize the variable in future before accessing it while execution.  private lateinit var courseName : String fun fetchCourseName (courseId: String) { courseName = courseRepository.getCourseName(courseId) } If you do not initialize your variable before accessing it you will get the exception UninitializedPropertyAccessException . If you want to check if the variable is initialized before accessing it you can use isInitialized property if ( this ::courseName.isInitialized) { // access courseName } else { // some default value } When you want to use lateinit then you can't use var variables, you can only use var variables. lateinit variables can be declared either inside a class or at the top level property. lateinit are only used for non-primitive variables. lateinit doesn't allow null values. lazy lazy is used for ini