Search code examples
kotlinkotlin-android-extensionskotlin-extensionrx-kotlin

Create New Instance of Kotlin Object


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))

Solution

  • I figured out my issue. I was passing in the same ArrayList to both quickSortOne() and quickSortTwo(). Since the ArrayList was being modified by the first method, the second method was being affected as well.