简体   繁体   English

在Scala中是否可以有一个将方法作为参数的通用方法?

[英]Is it possible in scala to have a generic method taking a method as an argument?

I would like to have: 我想拥有:

def myMethod[T < ???](f: T): Unit = {
    f()
}

The rest of the method is not really important but is it possible to replace ??? 该方法的其余部分并不是很重要,但是可以替换??? by somethind which would make sure T is a method 通过某种东西可以确保T是一个方法

and if possible to go even further and make sure the return type of T is something defined ? 如果可能的话,进一步确保T的返回类型已定义?

Like [T < (_*) => Int] [T < (_*) => Int]

Thank you. 谢谢。

Would defining a type , like in the following trivial example, address your need? 是否像下面的简单示例中那样定义type解决您的需求?

type Fcn = String => Int

def myMethod(s: String, f: Fcn): Unit = {
  println(f(s))
}

myMethod("hello", (s: String) => s.length)
// 5

You can use function literals: 您可以使用函数文字:

def myMethod[A, T](f: A => T) {
  f(someAValue)
}

or if you want functions that take no arguments: 或者如果您想要不带参数的函数:

def myMethod[T](f: () => T) {
  f()
}

But judging by your comments, it seems like you specifically want to reference methods, and query the method for information about itself, which is not a feature of basic Scala. 但是从您的评论来看,您似乎特别想引用方法,并在方法中查询有关其自身的信息,这不是基本Scala的功能。 You may be able to do some of that with reflection, but reflection is an area best avoided. 您也许可以使用反射来完成其中的一些操作,但是最好避免使用反射。

Technically, you can't directly pass a method, since a method is not a value that you can instantiate and pass-around. 从技术上讲,您不能直接传递方法,因为方法不是可以实例化和传递的值。 What is usually passed around is a function instance. 通常传递的是一个函数实例。 And when it appears that you're passing a method, the compiler is actually creating a function instance for you (method lifting or eta-expansion). 当您似乎正在传递方法时,编译器实际上是在为您创建一个函数实例(方法提升或eta扩展)。

But that is not going to work if you're looking to inspect meta data about that method (name, deprecation). 但是,如果您要检查有关该方法的元数据(名称,不赞成使用),那将是行不通的。 For that, you're probably looking for reflection. 为此,您可能正在寻找反思。 You can have your method take an instance of java.reflect.Method but that will require that you obtain that at call-site. 您可以让您的方法采用java.reflect.Method的实例,但这将要求您在调用站点上获得它。

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

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