当前位置: 动力学知识库 > 问答 > 编程问答 >

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 ?

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: