Reputation: 10672
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?
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
Reputation: 1734
In Scala, you can avoid using these methods in lambda processing, using the _
syntax and the bitwise operators:
_ & _
_ | _
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
Reputation: 4587
You can just use a function literal:
val op: (Boolean, Boolean) => Boolean =
if (input == "or")
_ || _
else
_ && _
Upvotes: 4
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