像Scala中的Java 8中一样的方法引用 [英] Method References like in Java 8 in Scala
问题描述
在此Java类中:
import java.util.function.*;
public class T {
public String func(String a) {
System.out.println("There we go: " + a);
return a;
}
public static void main(String... args) {
final Supplier<T> c = T::new;
final BiFunction<T, String, String> f = T::func;
final T t = c.get();
final String v = f.apply(t, "something");
System.out.println(v);
}
}
我可以获得对T
的构造函数和实例方法func
的方法引用.
I can get a method reference to the constructor of T
and to the instance method func
.
有没有办法在scala中做同样的事情,即获得
Is there a way to do the same in scala, i.e. to get
val c: () => T = ??? // default constructor of T as function
val f: (T, String) => String = ??? // instance method func of T as function
无需像这样包装它们:
val c: () => T = () => new T
val f: (T, String) => String = (t, arg) => t.func(arg)
即有没有一种方法像Java 8一样优雅,可以获取构造函数和实例方法引用来为这些事情获取scala函数?
i.e. is there a way which is as elegant as the Java 8 way to get constructor and instance method references to obtain scala functions for these things?
推荐答案
首先,让我们看一下Java代码到Scala的字面翻译:
First, let's have a look at a literal translation of the Java code to Scala:
class T {
def func(a:String) : String = {
println(s"There we go: $a")
a
}
}
object T {
def main(args: Array[String]) = {
val supplier = () => new T
val f = (t:T) => t.func _
val t = supplier()
val v = f(t)("something")
println(v)
}
}
在Scala中,函数是一等公民,因此不需要像Java Supplier
那样对生成的事物"进行特殊构造,因为它被建模为函数:f: () => T
(对应的Consumer
为f: T => ()
)
In Scala, functions are first class citizens, hence there's no need to have particular constructions for "things that generate", like the Java Supplier
, as it's modeled as a function: f: () => T
(same thing goes for its counterpart, the Consumer
as f: T => ()
)
我们刚刚说过,函数是一等公民,所以让我们看一下使用该范式的上述版本:
We just said that functions are first class citizens, so let's see a version of the above using this paradigm:
object Tfunc {
// let's remove the println side-effect from a function.
val func: String => String = a => s"There we go: $a"
def main(args: Array[String]) = {
println(func("something"))
}
}
在Scala中,没有对应的方法来获取构造函数引用,但是如果目标是使用功能方法,则Scala object
提供了一种简单的构造来保存函数,而无需实例化.
In Scala, there's no counterpart to obtain a constructor reference, but if the aim is to use a functional approach, Scala object
s offer a simple construct to hold functions and do not require to be instantiated.
这篇关于像Scala中的Java 8中一样的方法引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!