Links to methods like Java 8 in Scala

In this Java class:

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); } } 

I can get a reference to the T constructor method and the func instance method.

Is there a way to do the same in scala, i.e. receive

 val c: () => T = ??? // default constructor of T as function val f: (T, String) => String = ??? // instance method func of T as function 

without wrapping them:

 val c: () => T = () => new T val f: (T, String) => String = (t, arg) => t.func(arg) 

i.e. is there a way as elegant as Java 8's method of getting references to the constructor and method instance to get scala functions for these things?

+5
source share
2 answers

First, let's take a look at the literal translation of Java code into 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) } } 

In Scala, functions are first-class citizens, so there is no need to create specific constructs for β€œthings that generate”, like the Java Supplier , since it is modeled as a function: f: () => T (the same thing happens for its Consumer counterpart as f: T => () )

We just said that functions are first class citizens, so consider the version above using this paradigm:

 object Tfunc { // let 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 has no analogue to get a reference to a constructor, but if the goal is to use a functional approach, Scala object offers a simple construction for storing functions and does not require instantiation.

+2
source

Just like you do in java 8, you cannot. For the class constructor, I think there is no way to do this, other than how you did it.

For functions, you can use the placeholders parameters, which, in my opinion, are "cleaner".

 var t = new T() var func = t.func _ func("a") 

If you use case class , you can use apply method.

 case class C(a: String) var d = C.apply _ d("c") 

You can use the apply function for regular classes, but you must implement it yourself. For case classes, they are executed automatically.

+1
source

Source: https://habr.com/ru/post/1259203/


All Articles