Search code examples
scalaclasscompanion-object

Private value of a Scala class is not accessible in the companion Object


I have a Scala class and it's companion object (in Client.scala) as follows:

class Client(val key: Int) {
     private val num_bits = 5
}

object Client {
     val count_entries = Math.pow(2, num_bits).toInt
     println(count_entries)
}

However, it throws an error in the Client Object that not found: value num_bits. Could someone help?


Solution

  • You can use it like this:

    class Client(val key: Int) {
         private val num_bits = 5
    }
    
    object Client {
         val count_entries = Math.pow(2, new Client(0).num_bits)
         println(count_entries)
    }
    

    You have to create the object if you want use it.