Declaring new object in kotlin
In Kotlin, you can declare a new object using the object
keyword. Here are a few ways to do it:
1. Simple object declaration
object MyObject {
fun doSomething() {
println("Hello, world!")
}
}
This declares a new object called MyObject
with a single method doSomething()
.
2. Object with properties
object MyObject {
val name: String = "John"
val age: Int = 30
}
This declares an object with two properties: name
and age
.
3. Object with companion object
object MyObject {
companion object {
fun doSomething() {
println("Hello, world!")
}
}
}
This declares an object with a companion object, which is a special type of object that can be used to provide static methods and properties.
4. Object with inheritance
open class Animal {
open fun sound() {
println(" generic animal sound")
}
}
object Dog : Animal() {
override fun sound() {
println("Woof!")
}
}
This declares an object Dog
that inherits from the Animal
class and overrides the sound()
method.
5. Object with extension function
object MyObject {
fun String.uppercaseOrLowercase(): String {
return this.toUpperCase()
}
}
This declares an object with an extension function uppercaseOrLowercase()
that can be used on strings.
Note that in Kotlin, objects are not the same as classes. Objects are instances of classes, and they are created using the object
keyword. Classes, on the other hand, are declared using the class
keyword.