Scala self implements Boolean显示了几个错误

时间:2016-05-07 12:22:20

标签: scala boolean

我遵循了Scala"" Funcitonal Programming Principles的课程。作者:Martin Odersky。对于第4周的4.2视频" Objects Everywhere",我按照步骤实现了我自己的布尔类,但是eclipse显示了以下几个错误:

package week4

object Main{

   abstract class Boolean{

       def ifThenElse[T](e1: => T, e2: => T): T

       def && (b2: => Boolean): Boolean = ifThenElse(b2,False)
       def || (b2: => Boolean): Boolean = ifThenElse(True,b2)
       def unary_!: Boolean             = ifThenElse(False,True)    //error1

       def == (b2: Boolean): Boolean = ifThenElse(b2, b2.unary_!)   //error2
       def != (b2: Boolean): Boolean = ifThenElse(b2.unary_!, b2)   //error3
   }

   object True extends Boolean{
       def ifThenElse[T](e1: => T, e2: => T): T = e1
   }

   object False extends Boolean{
       def ifThenElse[T](e1: => T, e2: => T): T = e2
   }

   def main(args: Array[String]) {
      println("Hello, world!2")
      True.ifThenElse(println("True"), println("Flase"))
   }
}

error1:找到标识符所需的=

错误2:

此行的多个标记

  • 非法启动简单表达
  • 按名称参数创建():=> b2
  • 价值一元!不是week4.Main.Boolean
  • 的成员

误差3:

此行的多个标记

  • 按名称参数创建():=> b2
  • 价值一元!不是week4.Main.Boolean
  • 的成员

有没有人知道为什么会这样?

1 个答案:

答案 0 :(得分:4)

您需要unary_!:

之间的空格
def unary_! : Boolean             = ifThenElse(False,True)

或者,正如hezamu在评论中所指出的,你可以使用括号(有或没有空格)

def unary_!(): Boolean             = ifThenElse(False,True)

虽然值得注意的是there is a convention in Scala that parentheses on a no-args method indicate that it has side effects,但这种情况并非如此。

第三个选项,其中返回类型可以由编译器推断(如本例中的情况)是完全省略返回类型:

def unary_! = ifThenElse(False, True)