Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Booleans : code snippet

Tags:

scala

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.

like image 223
blue-sky Avatar asked Apr 17 '13 15:04

blue-sky


2 Answers

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.

like image 195
Randall Schulz Avatar answered Nov 06 '22 20:11

Randall Schulz


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.

like image 31
Joe F Avatar answered Nov 06 '22 20:11

Joe F