Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在scala中的对象内部使用方法?_Scala_Object - Fatal编程技术网

如何在scala中的对象内部使用方法?

如何在scala中的对象内部使用方法?,scala,object,Scala,Object,我在scala工作表中有这个示例代码。我不明白为什么我不能访问代码底部的函数 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]: St

我在scala工作表中有这个示例代码。我不明白为什么我不能访问代码底部的函数

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
}

此外,我还需要编写toList方法。我应该在哪里写?如果无法访问这些方法,如何测试它?

cons
不是
Stream2
实例的一部分。它是
Stream2
对象的单例(静态)方法。因此,访问它的唯一方法是通过对象调用它:

Stream2.cons(2,s)

要访问实例上的方法,必须将其添加到
trait
(因为它引用的是trait,而不是创建的最终对象)。否则,您可以将其添加到singleton并通过它调用。

我不知道此代码的具体功能,但是
s
Stream2[Int]
实例,而
cons
是一个伴生对象方法(您可以将其与
Stream2.cons
一起使用)。我可以在Stream2对象中使用cons吗?应用的方法似乎正在使用它。