user2012953
user2012953

Reputation:

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)
)

Upvotes: 5

Views: 2652

Answers (2)

Lucas
Lucas

Reputation: 23

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"
  }
}

Upvotes: 0

mikołak
mikołak

Reputation: 9705

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").

Upvotes: 7

Related Questions