0

I'm working through the Essential Scala textbook from Underscore, and when I try to use one of the examples from the command line using the :load command I get errors. [edit] I said command line, I meant console.

I have put the code into a file by itself, and then have tried to use it using the :load command.

sealed trait IntList {
  def product: Int =
    this match {
      case End => 1
      case Pair(hd, tl) => hd * tl.product
    }
}
case object End extends IntList
final case class Pair(head: Int, tail: IntList) extends IntList

I expected the code to compile and be usable, but I get these messages:

 error: pattern type is incompatible with expected type;
 found   : End.type
 required: IntList
      case End => 1

and

error: constructor cannot be instantiated to expected type;
 found   : Pair
 required: IntList
      case Pair(hd, tl) => hd * tl.product
  • Copy pasting this into a Scala project and running `sbt comile` works for me. What version of scala are you using? What is the `:load` command? – pedromss May 03 '19 at 14:27
  • Hi - I just edited the question, I realised I used the wrong terms, I said command line, but what I meant was console. I'm in the scala console, and use ':load filename' command, and that gives the errors I mentioned. All I know how to use at the moment is the Scala console. – Ogladr Kjarr May 03 '19 at 14:30
  • Scala version 2.12.7 – Ogladr Kjarr May 03 '19 at 14:34
  • Since the code compiles in a regular sbt project but does not work inside the console I would suggest you move away from the console. If that is not possible try typing the code in the console instead of loading a file and checking if the behaviour is still the same – pedromss May 03 '19 at 14:37
  • 2
    @OgladrKjarr use `:paste file` instead of `:load file` https://stackoverflow.com/questions/7383436/load-scala-file-into-interpreter-to-use-functions – Dmytro Mitin May 03 '19 at 14:48
  • @DmytroMitin thanks - that worked perfectly. Pedromss thanks for looking into it, I do need to leave the console, but I was hoping the learning resources I use will help with that. – Ogladr Kjarr May 03 '19 at 15:02

1 Answers1

0

Use :paste command in Scala REPL:

scala> :paste
// Entering paste mode (ctrl-D to finish)

sealed trait IntList {
  def product: Int =
    this match {
      case End => 1
      case Pair(hd, tl) => hd * tl.product
    }
}
case object End extends IntList
final case class Pair(head: Int, tail: IntList) extends IntList

// Exiting paste mode, now interpreting.

defined trait IntList
defined object End
defined class Pair

scala>

P.S. just press ctrl-D when you finished pasting all the lines.

Matthew I.
  • 1,793
  • 2
  • 10
  • 21