0

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!

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
wang kai
  • 1,673
  • 3
  • 12
  • 21
  • 4
    If it is not a case class you would need to write `new Id(f(value))` to create a new instance. For case classes the `new` keyword is not necessary – Harald Gliebe Jul 23 '21 at 03:06
  • 2
    @HaraldGliebe is correct, except in Scala 3 where the need for `new` has been relaxed and your code [compiles and runs](https://scastie.scala-lang.org/C3jcCzq4T1ODKL2CPULXkQ) without error. – jwvh Jul 23 '21 at 04:55
  • https://stackoverflow.com/questions/68493548/why-this-class-have-to-be-case-class – Dmytro Mitin Jul 23 '21 at 08:52

1 Answers1

1

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)
}
Jack Leow
  • 21,945
  • 4
  • 50
  • 55