Ori Popowski
Ori Popowski

Reputation: 10672

Scala - two operand or/and functions

In Java there are static and/or functions which receive two boolean operands and return the correct result: logicalAnd and logicalOr (both located in java.lang.Boolean) [1]:

public static boolean logicalAnd(boolean a, boolean b)
public static boolean logicalOr(boolean a, boolean b)

I'm looking for a similar concept in the Scala standard library. Is there any?

Edit

I know Scala can call Java functions, but this code won't compile since Java's functions are not high-order, so it's not usable for me:

val op =
  if (input == "or") java.lang.Boolean.logicalOr
  else java.lang.Boolean.logicalAnd

[1] https://docs.oracle.com/javase/8/docs/api/java/lang/Boolean.html

Upvotes: 1

Views: 123

Answers (3)

gianluca aguzzi
gianluca aguzzi

Reputation: 1734

In Scala, you can avoid using these methods in lambda processing, using the _ syntax and the bitwise operators:

  • Boolean::logicalAnd => _ & _
  • Boolean::logicalOr => _ | _

For example, if you have in Java something like this:

Stream.of(/* .. some objects .. */)
      .map(/* some function that returns a boolean */)
      .reduce(Boolean::logicalOr);

In Scala is possible to write using _ syntax:

LazyList.fill(/* ... */)
     .map(/* ... */)
     .reduce(_ & _) // or | or ^

Upvotes: 0

Matthias Berndt
Matthias Berndt

Reputation: 4587

You can just use a function literal:

val op: (Boolean, Boolean) => Boolean =
  if (input == "or")
    _ || _
  else
    _ && _

Upvotes: 4

Jasper-M
Jasper-M

Reputation: 15086

The fact that

val op =
  if (input == "or") java.lang.Boolean.logicalOr
  else java.lang.Boolean.logicalAnd

doesn't compile has nothing to do with those methods being defined in Java or in Scala.

The code you posted actually compiles in Scala 3. In Scala 2 you have to be explicit when you want to turn a method into a function value:

val op =
  if (input == "or") java.lang.Boolean.logicalOr _
  else java.lang.Boolean.logicalAnd _

Upvotes: 4

Related Questions