简体   繁体   English

如何将 java 谓词转换为 scala 谓词

[英]How to covert java predicate to scala predicate

I have a java method which is accepting我有一个正在接受的 java 方法

predicate(Predicate<T> predicate)

my java class is我的 java class 是

class Employee {

  String getEmployeeId() {
    return "";
  }

  boolean isManager() {
    return true;
  }
}

In java I can call在 java 我可以打电话

predicate(Employee::isManager)

how to do this in scala?如何在 scala 中执行此操作?

This should work in scala这应该在 scala 中工作

predicate[Employee](_.isManager)

A Java Predicate is a Functional interface that, from the doc, "Represents a predicate (boolean-valued function) of one argument" A Java Predicate 是一个函数式接口,来自文档,“表示一个参数的谓词(布尔值函数)”

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.在 Scala 语言中默认支持函数式接口的概念,因为 Scala 是多范式语言 object 面向函数式编程。

So you need to think about the predicate interface like a lambda function that returns a boolean for certain input.因此,您需要考虑诸如 lambda function 之类的谓词接口,它会为某些输入返回 boolean。

for example:例如:

predicate(p => p.isManager)

But in the scala language, for this scenario you can use the special character _ so:但在 scala 语言中,对于这种情况,您可以使用特殊字符 _,因此:

predicate(_.isManager)

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. 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 . scala 中的谓词类型将是Function1[T, Boolean]或带有语法糖T => Boolean

Transforming your code to scala, the class that you have will be将您的代码转换为 scala,您将拥有的 class

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 .在这里试试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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