'object.type does not take parameter error

Following is the code snippet I am using from play with scala book. It works well in the framework but when I try in the commndline it gives the error

 error: Product.type does not take parameters
     var products = Set(Product(5018206244611L, "Tom", "Zebra"))

Below is the code I used

case class Product(ean: Long, name: String, description: String)
object Product {
  var products = Set(Product(5018206244611L, "Tom", "Zebra"))
  def findAll = products.toList.sortBy(_.ean)
}

In one of the controller file tutorial uses Product.apply and Product.unapply. What does Product.apply and Product.unapply indicate when they are not defined inside the object and gives me error when I type them in console. FOllowing is the code which uses Product.apply and Product.unapply

private val productForm: Form[Product] = Form(
  mapping(
    "ean" -> longNumber.verifying(
      "validation.ean.duplicate", Product.findByEan(_).isEmpty),
    "name" -> nonEmptyText,
    "description" -> nonEmptyText)(Product.apply)(Product.unapply)
)


Solution 1:[1]

The Scala REPL (commandline) has a few differences compared to "normal" compilation. Other than the inability to define packages the other major one is that it executes statements one-by-line.

The above means that, in the Scala REPL, you did not create a class with a companion object with your second code block; rather, you created the Product case class, and then "shadowed" it with a new Product module.

The solution is to use the :paste command in the REPL so that you input both definitions at the same time.

Regarding your second question - apply is an application method (what you call with foo(...) - all FunctionN instances have it, for example), unapply is an extractor method (used for pattern matching - case classes get it for "free").

Solution 2:[2]

Now that we're 8 years in the future, if you use ammonite repl you can put both the class definition and object definition in a block like this:

{
  case class Person(name: String, id: Int) 
  
  object Person {
    def foo = "bar"
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 miko?ak
Solution 2 Lucas