Kotlin Class: Logger class with companion object for logging
Write a Kotlin program that creates a class 'Logger' with a companion object that provides logging functionality.
Pre-Knowledge (Before You Start!)
Before attempting this exercise, you should be familiar with the following concepts:
- Classes and Objects: Understanding how to define and use classes in Kotlin.
- Companion Objects: Special objects in Kotlin that allow you to define static-like methods inside a class.
- Private Constructors: Preventing direct instantiation of a class to enforce controlled access.
- Singleton Pattern: Using a companion object to ensure only one instance of logging functionality is used.
- Printing to Console: Using println() to display messages.
Hints (Try Before Looking at the Solution!)
Try to solve the problem using these hints:
- Hint 1: Define a class named Logger with a private constructor to prevent object creation.
- Hint 2: Inside the Logger class, define a companion object.
- Hint 3: Add a function inside the companion object to log messages.
- Hint 4: Use println() to display the log message in a formatted way.
- Hint 5: In the main() function, call the log function using Logger.log("message").
Sample Solution:
Kotlin Code:
class Logger private constructor() {
companion object {
fun log(message: String) {
println("Logging: $message")
}
}
}
fun main() {
Logger.log("This is a log message.")
}
Sample Output:
Logging: This is a log message
Explanation:
In the above exercise -
- First we define a "Logger" class with a private constructor to prevent direct instantiation of the class. Inside the "Logger" class, we have a companion object that provides logging functionality.
- The companion object contains a log function that takes a message parameter and prints a log message. In this example, it simply prints the message with "Logging: ".
- In the "main()" function, we call the log function of the Logger class through the companion object by using the syntax Logger.log("message"). This logs the provided message.
Kotlin Editor:
Previous: Person class with nested ContactInfo class.
Next: Data class point with destructuring declaration.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics