Constructing a cumulative distribution function from a histogram
Your problem starts here:

val cdfData: MutableMap&lt;Int, Double&gt; = mutableMapOf()


This is the data that you want to your CDF class, but anyone can make a mutable map anywhere and use it for tons of things. So this is what you want to hide. So put this inside a CDFBuilder

class CDFBuilder {
     private val cdfData: MutableMap = mutableMapOf&lt;Int, Double&gt;()

     fun withData(a: Int, b: Double): CDFBuilder {
          // verification and stuff
          cdfData[a] = b
          return this
     }
}


Now, the problem is to build the CDF class without letting anyone else do it, right? There are a few options here:


Make a copy of the cdfData public from the CDFBuilder and read it in the CDF constructor, passing a CDFBuilder to the constructor.


Or 2, make a private constructor on the CDF-class, allowing it to only be constructed from the builder:

class CDF private constructor(val map: SortedMap&lt;Int, Double&gt;) {

    class CDFBuilder {
        private val cdfData: MutableMap = mutableMapOf&lt;Int, Double&gt;()

        fun withData(a: Int, b: Double): CDFBuilder {
            // verification and stuff
            cdfData[a] = b
            return this
        }

        fun build(): CDF {
            return CDF(map.toSortedMap())
        }
    }
}