Search code examples
scalacompanion-object

Unable to create companion class instance in companion object method


What's wrong with this code:

class Trivials(s:String){
  private val x = 0
}

object Trivials {

  def main(args: Array[String]): Unit = {
    Trivials t = new Trivials("Trivials")
 }
}

Both class and object are defined in same source file, hence they are companion.

Error message is as: 'Cannot resolve symbol t'


Solution

  • Wrong syntax (You are using Java syntax) for object creation. In case of Scala you need not mention the type in front of the variable t it will be automatically inferred.

    Trivials t = new Trivials("Trivials")
    

    Scala syntax

    val t = new Trivials("Trivials")