简体   繁体   中英

Rewrite Scala && to and

I am trying to rewrite Scala's && to and in the following way (I love python, that's why I'm trying to do this):

def and(p1: () => Boolean, p2: () => Boolean): Boolean = p1() && p2()

However, when I try to use it with, eg:

def and(p1: () => Boolean, p2: () => Boolean): Boolean = p1() && p2()
if ((l < h.length) and (h(l) > h(i)))

(I put the def just on the line before only for debugging, to make sure it's not a visibility problem), I get:

Error:(40, 26) value and is not a member of Boolean
  if ((l < h.length) and (h(l) > h(i)))

What is going on here???

The way to do what you want is something like this:

  object Pythonians {
    implicit class Bool(val b: Boolean) extends AnyVal { 
      def and(p: => Boolean) = b && p
    }
  }

Now you can do things like:

  import Pythonians._
  3 < 4 and "foo" == "bar"

But, do yourself a favor, and ... don't. If you "love python" so much, why don't you write code in python? If you are taking time to learn scala anyway, might as well give it's own syntax and idioms a try ... Who knows, maybe you'll grow to love it even more than you love python? And other people, who have to read the code you write will appreciate not having to figure out the whole new language too.

With your definition, you'd call it as

and(() => l < h.length, () => h(l) > h(i))

Since the parameters have type () => Boolean , that's what you need to pass, not Boolean . Scala has special syntax to work around this called by-name parameters, which you can see in Dima's answer. Using it (but no implicit conversion), you'd write

def and(p1: => Boolean, p2: => Boolean): Boolean = p1 && p2
and(l < h.length, h(l) > h(i))

It means that you pass an expression of type Boolean as the argument, but it isn't calculated before calling the method, as usual, but at the place it's used. So in this case if p1 evaluates to false , p2 will never be evaluated, just like && .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM