blue-sky
blue-sky

Reputation: 53786

Scala Booleans : code snippet

I'm using some scala code taken from a Scala courers on coursera :

package src.functional.week4

abstract class Boolean {

  def ifThenElse[T](t: => T, e: => T): T

  def && (x: => Boolean): Boolean = ifThenElse(x, false)

}

The line def && (x: => Boolean): Boolean = ifThenElse(x, false) gives this compile time error :

type mismatch; found : scala.Boolean(false) required: src.functional.week4.Boolean

Here is the code snippet from the video :

enter image description here

Do I need to change the code in order for it to compile ?

When I create the new 'false' object using

  object false extends Boolean {
      def ifThenElse[T](t: => T, e: => t) = e
  }

I receive the error :

Multiple markers at this line - identifier expected but 'false' found.

I am defining the object within the the same class as 'abstract class Boolean'. I am unable to create a new object of type 'false' as the Eclipse IDE does not allow this.

Upvotes: 6

Views: 820

Answers (2)

Joe F
Joe F

Reputation: 4252

The code in the lecture does not compile because true and false are reserved words and can't be redefined. Try using True and False instead.

Upvotes: 4

Randall Schulz
Randall Schulz

Reputation: 26486

Your code (and Martin's) defines a new Boolean even though it's pre-defined / built-in in Scala.

The problem you're encountering is that you have not defined a new false to supercede the built-in false and the built-in false is not compatible with your re-defined Boolean.

Upvotes: 6

Related Questions