Thursday 18 January 2018

Kotlin: Define singleton objects

By using 'object' keyword, you can define singleton objects.

Syntax
object ObjectName{

}

Ex
object mySingleTonObj {
     var x: Int = 10
     var y: Int = 20
 }

You can access the member variables and functions of singleton object using the object name directly.

Ex
mySingleTonObj.x
mySingleTonObj.y

Find the below working application.

HelloWorld.kt
class MyClass {
 object mySingleTonObj {
  var x: Int = 10
  var y: Int = 20
 }

 fun printSingletonObj() {
  println("Value of x is  : ${mySingleTonObj.x}")
  println("Value of y is  : ${mySingleTonObj.y}")
 }
}

fun main(args: Array<String>) {
 var obj = MyClass()

 obj.printSingletonObj()
}

Output
Value of x is  : 10
Value of y is  : 20

Can a singleton object has super type?
Yes, a singleton has super types.

Ex
         object mySingleTonObj : Arithmetic {
                 override fun sum(x: Int, y: Int): Int {
                          return x + y
                 }
         }

Find the below working application.


HelloWorld.kt
interface Arithmetic {
 fun sum(x: Int, y: Int): Int
}

class MyClass {
 object mySingleTonObj : Arithmetic {
  override fun sum(x: Int, y: Int): Int {
   return x + y
  }
 }

 fun getSum(x: Int, y: Int): Int {
  return mySingleTonObj.sum(x, y)
 }

}

fun main(args: Array<String>) {
 var obj = MyClass()
 var result = obj.getSum(10, 20)

 println("Sum of 10 and 20 is : $result")
}

Output
Sum of 10 and 20 is : 30

Can object declaration be local?
Object declarations can't be local. For ex, you can't define them inside a function.


HelloWorld.kt

fun main(args: Array<String>) {
 object mySingleTonObj {
  fun sum(x: Int, y: Int): Int {
   return x + y
  }
 }

}

When you try to compile above program, you will end up in below error.


Named object 'mySingleTonObj' is a singleton and cannot be local. Try to use anonymous object instead




Previous                                                 Next                                                 Home

No comments:

Post a Comment