Kotlin Class: Logger class with companion object for logging
Kotlin Class: Exercise-16 with Solution
Write a Kotlin program that creates a class 'Logger' with a companion object that provides logging functionality.
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/kotlin-exercises/class/kotlin-class-exercise-16.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics