我无法弄清楚为什么我没有得到这样的实例方法错误

时间:2015-10-08 17:04:46

标签: scala

这是关于Coursera Scala课程的问题。请回答为什么我的代码无法正常工作,因为我通过代码执行调试器时没有遇到这样的实例方法错误。该错误不会阻止代码运行,它总是说我的过滤的tweetSet是空的,但它应该包括Tom和Mike Tweet。

的具体错误
val foo = temp.filter(_.retweets > 4)

TrueTweet = No such instance method: 'objsets.test$$anonfun$2.trueTweet '
No such instance method: 'objsets.test$$anonfun$2.objsets$test$$trueTweet '
temp = No such instance method: 'objsets.test$$anonfun$2.temp '
No such instance method: 'objsets.test$$anonfun$2.objsets$test$$temp '
falseTweet = No such instance method: 'objsets.test$$anonfun$2.falseTweet '
No such instance method: 'objsets.test$$anonfun$2.objsets$test$$falseTweet '

我的Test

class Test extends FunSuite {
  val trueTweet = new Tweet("Tom", "Hello", 45)
  val falseTweet = new Tweet("Mike", "HellO", 44)
  var temp: TweetSet = new NonEmpty(new Tweet("Jon", "I am the best", 2), new Empty(), new Empty())
  temp = temp.incl(trueTweet)
  temp = temp.incl(falseTweet)

  def printFunc(t: Tweet): Unit = {
    println(t)
  }

  val foo = temp.filter(_.retweets > 4)
  foo.foreach(printFunc)
}

TweetSet

的一部分
class TweetSet {
  def filter(p: Tweet => Boolean): TweetSet = filterAcc(p, new Empty)
}

Tweet上课

class Tweet(val user: String, val text: String, val retweets: Int) {
  override def toString: String =
    "User: " + user + "\n" + "Text: " + text + " [" + retweets + "]"
}

Empty

的一部分
class Empty extends TweetSet {
  def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet = this

  def foreach(f: Tweet => Unit): Unit = ()
}

NonEmpty

的一部分
class NonEmpty(elem: Tweet, left: TweetSet, right: TweetSet) extends TweetSet {
  def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet = {
    var accHelper = acc
    foreach(t => if (p(t)) accHelper.incl(t))
    accHelper
  }

  def foreach(f: Tweet => Unit): Unit = {
    f(elem)
    left.foreach(f)
    right.foreach(f)
  }

 def incl(x: Tweet): TweetSet = {
    if (x.text < elem.text) new NonEmpty(elem, left.incl(x), right)
    else if (elem.text < x.text) new NonEmpty(elem, left, right.incl(x))
    else this
 }
}

1 个答案:

答案 0 :(得分:1)

测试类错误,请参阅http://www.scalatest.org/getting_started_with_fun_suite以查看应如何设置。

class Test extends FunSuite {
  test("what are you testing") {
    val trueTweet = new Tweet("Tom", "Hello", 45)
    val falseTweet = new Tweet("Mike", "HellO", 44)
    var temp: TweetSet = new NonEmpty(new Tweet("Jon", "I am the best", 2), new Empty(), new Empty())
    temp = temp.incl(trueTweet)
    temp = temp.incl(falseTweet)

    def printFunc(t: Tweet): Unit = {
      println(t)
    }

    val foo = temp.filter(_.retweets > 4)
    foo.foreach(printFunc)
  }

  test("what are you testing") {
    //other test code
  }
}