Search code examples
scalaclassinstantiationcase-class

Why this class have to be case class?


This class:

class Id[A](value: A) {
 def map[B](f: A => B): Id[B] = Id(f(value))
 def flatMap[B](f: A => Id[B]): Id[B] = f(value)
}

got error:"not found value Id" at line 2

it's fine if the class is a case class:

case class Id[A](value: A) {

I don't know why this class have to be case class,Thanks!


Solution

  • It doesn't need to be a case class per se. It just needs to have a corresponding apply on its companion object to create a new instance (which case classes automatically do for you).

    If you really don't want it to be a case class for whatever reason, you can define the companion apply yourself like so:

    class Id[A](value: A) {
     def map[B](f: A => B): Id[B] = Id(f(value))
     def flatMap[B](f: A => Id[B]): Id[B] = f(value)
    }
    object Id {
      def apply[A](value: A) = new Id(value)
    }
    

    Alternatively, as others have pointer out, you can explicitly instantiate Id with the new keyword:

    class Id[A](value: A) {
     def map[B](f: A => B): Id[B] = new Id(f(value))
     def flatMap[B](f: A => Id[B]): Id[B] = f(value)
    }