3

I have this sample code in a scala worksheet. I do not understand why I can not access to the functions as at the bottom of the code.

object chapter5 {
  println("Welcome to the Scala worksheet")

  trait Stream2[+A] {
    def uncons: Option[(A, Stream2[A])]
    def isEmpty: Boolean = uncons.isEmpty
  }
  object Stream2 {

    def empty[A]: Stream2[A] =
      new Stream2[A] { def uncons = None }

    def cons[A](hd: => A, tl: => Stream2[A]): Stream2[A] =
      new Stream2[A] {
        lazy val uncons = Some((hd, tl))
      }

    def  apply[A](as: A*): Stream2[A] =
      if (as.isEmpty) empty
      else cons(as.head, apply(as.tail: _*))
  }

  val s = Stream2(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    s.isEmpty //I can access to the function declared in the trait
    s.cons // error  // I can not access to the function declared in the object
}

In addition I need to write the toList method. Where should I write it? How can I test it if I can not access to the methods ?

1
  • I do not know what this code exactly does, but s is a Stream2[Int] instance while cons is a companion object method (you can use it with Stream2.cons). Commented Mar 4, 2015 at 17:03

1 Answer 1

4

cons is not part of the Stream2 instance. It is a singleton(static) method of the Stream2 object. So, the only way to access it is by calling it through the object:

Stream2.cons(2,s)

To access methods on the instance, you would have to add it to the trait (since it is referencing the trait and not the final object created). Otherwise, you could add it to the singleton and call it through that.

Sign up to request clarification or add additional context in comments.

1 Comment

can I use cons inside the Stream2 object? the method apply seems to be using it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.