As far as I got in the case of case class companion object is generated by the compiler automatically.
case class Clas(i: Int)
But in my case I want to add some fatory method apply(s: String): Clas for convenience. So defined object myself as:
object Clas {
def apply(s: String) = //create Clas
}
How does it work? Why does methods from compiler-generated object are still available?
The compiler merges your methods with the synthetic ones in the companion object:
scala> :past
// Entering paste mode (ctrl-D to finish)
case class Clas(i: Int)
object Clas { def apply(s: String): Clas = null }
// Exiting paste mode, now interpreting.
defined class Clas
defined object Clas
scala> Clas.apply _
<console>:13: error: ambiguous reference to overloaded definition,
both method apply in object Clas of type (i: Int)Clas
and method apply in object Clas of type (s: String)Clas
match expected type ?
Clas.apply _
^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With