# Objects In this chapter, you'll expand your understanding of classes by exploring object declarations. This knowledge will help you efficiently manage behavior across your projects. ## Object declarations In Kotlin, you can use object declarations to declare a class with a single instance. In a sense, you declare the class and create the single instance at the same time. Object declarations are useful when you want to create a class to use as a single reference point for your program or to coordinate behavior across a system. Tip: A class that has only one instance that is easily accessible is called a singleton. Objects in Kotlin are lazy, meaning they are created only when accessed. Kotlin also ensures that all objects are created in a thread-safe manner so that you don't have to check this manually. To create an object declaration, use the `object` keyword: ```KOTLIN object DoAuth {} ``` Following the name of your `object`, add any properties or member functions within the object body defined by curly braces `{}`. Note: Objects can't have constructors, so they don't have headers like classes. For example, let's say that you wanted to create an object called `DoAuth` that is responsible for authentication: ```KOTLIN object DoAuth { fun takeParams(username: String, password: String) { println("input Auth parameters = $username:$password") } } fun main(){ // The object is created when the takeParams() function is called DoAuth.takeParams("coding_ninja", "N1njaC0ding!") // input Auth parameters = coding_ninja:N1njaC0ding! } ``` The object has a member function called `takeParams` that accepts `username` and `password` variables as parameters and prints a string to the console. The `DoAuth` object is only created when the function is called for the first time. Note: Objects can inherit from classes and interfaces. For example: ```KOTLIN interface Auth { fun takeParams(username: String, password: String) } object DoAuth : Auth { override fun takeParams(username: String, password: String) { println("input Auth parameters = $username:$password") } } ``` ### Data objects To make it easier to print the contents of an object declaration, Kotlin has data objects. Similar to data classes, which you learned about in the beginner tour, data objects automatically come with additional member functions: `toString()` and `equals()`. Tip: Unlike data classes, data objects do not come automatically with the `copy()` member function because they only have a single instance that can't be copied. To create a data object, use the same syntax as for object declarations but prefix it with the `data` keyword: ```KOTLIN data object AppConfig {} ``` For example: ```KOTLIN data object AppConfig { var appName: String = "My Application" var version: String = "1.0.0" } fun main() { println(AppConfig) // AppConfig println(AppConfig.appName) // My Application } ``` For more information about data objects, see [Data objects](object-declarations.html#data-objects). ### Companion objects In Kotlin, a class can have an object: a companion object. You can only have one companion object per class. A companion object is created only when its class is referenced for the first time. Any properties or functions declared inside a companion object are shared across all class instances. To create a companion object within a class, use the same syntax for an object declaration but prefix it with the `companion` keyword: ```KOTLIN companion object Bonger {} ``` Note: A companion object doesn't have to have a name. If you don't define one, the default is `Companion`. To access any properties or functions of the companion object, reference the class name. For example: ```KOTLIN class BigBen { companion object Bonger { fun getBongs(nTimes: Int) { repeat(nTimes) { print("BONG ") } } } } fun main() { // Companion object is created when the class is referenced for the // first time. BigBen.getBongs(12) // BONG BONG BONG BONG BONG BONG BONG BONG BONG BONG BONG BONG } ``` This example creates a class called `BigBen` that contains a companion object called `Bonger`. The companion object has a member function called `getBongs()` that accepts an integer and prints `"BONG"` to the console the same number of times as the integer. In the `main()` function, the `getBongs()` function is called by referring to the class name. The companion object is created at this point. The `getBongs()` function is called with parameter `12`. For more information, see [Companion objects](object-declarations.html#companion-objects). ## Practice Implement a data object for order tracking : You run a coffee shop and have a system for tracking customer orders. Consider the code below and complete the declaration of the second data object so that the following code in the `main()` function runs successfully: : ```KOTLIN interface Order { val orderId: String val customerName: String val orderTotal: Double } data object OrderOne: Order { override val orderId = "001" override val customerName = "Alice" override val orderTotal = 15.50 } data object // Write your code here fun main() { // Print the name of each data object println("Order name: $OrderOne") // Order name: OrderOne println("Order name: $OrderTwo") // Order name: OrderTwo // Check if the orders are identical println("Are the two orders identical? ${OrderOne == OrderTwo}") // Are the two orders identical? false if (OrderOne == OrderTwo) { println("The orders are identical.") } else { println("The orders are unique.") // The orders are unique. } println("Do the orders have the same customer name? ${OrderOne.customerName == OrderTwo.customerName}") // Do the orders have the same customer name? false } ``` : ```KOTLIN interface Order { val orderId: String val customerName: String val orderTotal: Double } data object OrderOne: Order { override val orderId = "001" override val customerName = "Alice" override val orderTotal = 15.50 } data object OrderTwo: Order { override val orderId = "002" override val customerName = "Bob" override val orderTotal = 12.75 } fun main() { // Print the name of each data object println("Order name: $OrderOne") // Order name: OrderOne println("Order name: $OrderTwo") // Order name: OrderTwo // Check if the orders are identical println("Are the two orders identical? ${OrderOne == OrderTwo}") // Are the two orders identical? false if (OrderOne == OrderTwo) { println("The orders are identical.") } else { println("The orders are unique.") // The orders are unique. } println("Do the orders have the same customer name? ${OrderOne.customerName == OrderTwo.customerName}") // Do the orders have the same customer name? false } ``` Create an object declaration : Create an object declaration that inherits from the `Vehicle` interface to create a unique vehicle type: `FlyingSkateboard`. Implement the `name` property and the `move()` function in your object so that the following code in the `main()` function runs successfully: : ```KOTLIN interface Vehicle { val name: String fun move(): String } object // Write your code here fun main() { println("${FlyingSkateboard.name}: ${FlyingSkateboard.move()}") // Flying Skateboard: Glides through the air with a hover engine println("${FlyingSkateboard.name}: ${FlyingSkateboard.fly()}") // Flying Skateboard: Woooooooo } ``` : ```KOTLIN interface Vehicle { val name: String fun move(): String } object FlyingSkateboard : Vehicle { override val name = "Flying Skateboard" override fun move() = "Glides through the air with a hover engine" fun fly(): String = "Woooooooo" } fun main() { println("${FlyingSkateboard.name}: ${FlyingSkateboard.move()}") // Flying Skateboard: Glides through the air with a hover engine println("${FlyingSkateboard.name}: ${FlyingSkateboard.fly()}") // Flying Skateboard: Woooooooo } ``` Validate an email address before creating a user : You are building a user registration module for an app. You want to keep email validation associated with the `User` class but don't want to create an unnecessary `User` instance if the email address is invalid. : For this exercise, consider an email address valid if it contains both `@` and `.`. Complete the data class so that the following code in the `main()` function runs successfully: : Hint : Add an email validation function in a companion object for the `User` class so that you can call the function directly on `User`. : ```KOTLIN data class User(val name: String, val email: String) { // Write your code here } fun main() { val candidates = listOf( Pair("Alice", "alice@example.com"), Pair("Bob", "bob2example-com") ) for ((name, email) in candidates) { if (User.isValidEmail(email)) { val user = User(name, email) println("Registered: ${user.name}, ${user.email}") // Registered: Alice, alice@example.com } else { println("Error: '${email}' is not valid. The email should contain '@' and '.'") // Error: 'bob2example-com' is not valid. The email should contain '@' and '.' } } } ``` : ```KOTLIN data class User(val name: String, val email: String) { companion object { fun isValidEmail(email: String): Boolean = email.contains('@') && email.contains('.') } } fun main() { val candidates = listOf( Pair("Alice", "alice@example.com"), Pair("Bob", "bob2example-com") ) for ((name, email) in candidates) { if (User.isValidEmail(email)) { val user = User(name, email) println("Registered: ${user.name}, ${user.email}") // Registered: Alice, alice@example.com } else { println("Error: '${email}' is not valid. The email should contain '@' and '.'") // Error: 'bob2example-com' is not valid. The email should contain '@' and '.' } } } ``` : Tip: As an extension of this exercise, try using functions in companion objects as factory methods to construct instances of a class. For an example and more information about this pattern, see [Companion objects](object-declarations.html#companion-objects). ## See also * [Previous step](kotlin-tour-intermediate-classes-interfaces.html) * [Next step](kotlin-tour-intermediate-open-special-classes.html)