Donbeo
Donbeo

Reputation: 17617

how to use method inside an object in scala?

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 ?

Upvotes: 3

Views: 3329

Answers (1)

Justin Pihony
Justin Pihony

Reputation: 67075

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.

Upvotes: 4

Related Questions