dinesh c
dinesh c

Reputation: 1

How to covert java predicate to scala predicate

I have a java method which is accepting

predicate(Predicate<T> predicate)

my java class is

class Employee {

  String getEmployeeId() {
    return "";
  }

  boolean isManager() {
    return true;
  }
}

In java I can call

predicate(Employee::isManager)

how to do this in scala?

Upvotes: 0

Views: 405

Answers (3)

Alfilercio
Alfilercio

Reputation: 1118

In scala we have lambdas, but the language doesn't have that more specific lambda like Predicate, that will be a function, that when called, will return a Boolean.

The type of Predicate in scala would be a Function1[T, Boolean] or with syntactic sugar T => Boolean.

Transforming your code to scala, the class that you have will be

class Employee {
  def getEmployeeId():String = {
    ""
    }

  def isManager(): Boolean = {
    true
    }
}

and the definition of the method predicate:

def predicate[T](f: T => Boolean): UnknownType = ???

To apply:

predicate[Employee](x => x.isManager)
// x will be of type Employee, as setted in the type parameter
//or with sugar
predicate[Employee](_.isManager) 
//you only use the obtained parameter once,
//so we can call it "wildcard" or `_`, and get it's method

try it here.

Upvotes: 1

gccodec
gccodec

Reputation: 342

A Java Predicate is a Functional interface that, from the doc, "Represents a predicate (boolean-valued function) of one argument"

In the Scala language the concept of functional interface are supported by default, because Scala is a multi-paradigm language object oriented and functional programming.

So you need to think about the predicate interface like a lambda function that returns a boolean for certain input.

for example:

predicate(p => p.isManager)

But in the scala language, for this scenario you can use the special character _ so:

predicate(_.isManager)

Upvotes: 1

Ivan Stanislavciuc
Ivan Stanislavciuc

Reputation: 7275

This should work in scala

predicate[Employee](_.isManager)

Upvotes: 1

Related Questions