Create New Instance of Kotlin Object

Adam Hurwitz picture Adam Hurwitz · Nov 1, 2017 · Viewed 28.1k times · Source

I have an object QuickSort that I am attempting to create 2 instances of. When I try to create 2 separate instances I can see that it is only using one instance because I have a count in the QuickSort class that is inaccurate. Kotlin does not use new in the syntax, so how would I go about this?

object QuickSort {
      var count = 0;
      quickSortOne(...){
          ...
          count++
          ...
      }
      quickSortTwo(...){
          ...
          count++
          ...
      }
  } 

Here is how I am attempting to create my 2 instances.My goal is to have quickSort1 and quickSort2 be 2 separate instances.

var quickSort1 = QuickSort
quickSort1.quickSortOne(...)

var quickSort2 = QuickSort
quickSort2.quickSortTwo(...)

Attempted Solution: Converting QuickSort from an object to a class. This still results in the same instance being used as seen by the count of the second method including the first calls count.

class QuickSort {
      var count = 0;
      quickSortOne(...){
          ...
          count++
          ...
      }
      quickSortTwo(...){
          ...
          count++
          ...
      }
  }

...

var quickSortFirst = QuickSort()
printTest(quickSortFirst.quickSortFirst(arrayList, 0, arrayList.size - 1))

var quickSortLast = QuickSort()
printTest(quickSortLast.quickSortLast(arrayList, 0, arrayList.size - 1))

Answer

Kiskae picture Kiskae · Nov 1, 2017

object is a kotlin's version of a singleton. By using it you specify that there will only be 1 instance that is shared by all its users.

Turn it into a class and you will be able to create individual instances.