4/22/2023 0 Comments Internal function kotlinQ #1) What is the difference between – object and companion object in Kotlin?Īnswer: Companion objects are similar to objects, but they have a lot of differences.Ĭompanion objects need to be necessarily defined in another class. In other words, the function createConnection is acting like a FACTORY for creating objects of the type DatabaseConneciton. So, above, we are essentially creating an object of the type DatabaseConnection using the static method createConnection declared inside the companion object block. In the main function, we have used the “createConnection” method to instantiate the object of type DatabaseConnection and separately defined initialized specific property like userName.We have declared a companion object which contains some static variables – PORT and HOST and a function named createConnection which returns an object of type DatabaseConnection (i.e.We have a class DatabaseConnection which has connectionName and userName as its constructor and member parameters respectively and get a full connection method that returns the appended connection String. ![]() Let’s try to understand the above example: The companion object can be declared within an existing class and the functions or parameters can be defined inside the companion object declaration.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |