batman
batman

Reputation: 3685

Scala's type equivalent in Java

In Scala people write:

type Par[A] = ExecutorService => Future[A]

and they are referring to Par like this:

def run[A](s: ExecutorService)(a: Par[A]): Future[A] = a(s)

whats the equivalent of type(Scala) in Java?

Upvotes: 2

Views: 130

Answers (2)

Boris the Spider
Boris the Spider

Reputation: 61198

This is a curried function that takes a ExecutorService and returns a function that takes an Par<A> and returns a Future<A>.

Curried functions in Java can be emulated by methods that return objects. So, assume we have a interface:

@FunctionalInterface
interface Par<A> {
    Future<A> apply(ExecutorService ex);
}

We cannot alias Function<ExecutorService, Future<A>> to the interface Par, but you could extend that interface:

@FunctionalInterface
interface Par<A> extends Function<ExecutorService, Future<A>> {
}

It doesn't matter overmuch - type aliasing is not supported in Java, and there are several workarounds, some uglier than others.

We need an Object that takes closes on an ExecutorService and returns a Function<Par<A>, Future<A>>

<A> Function<Par<A>, Future<A>> withExecutor(ExecutorService s) {
    return a -> a.apply(s);
}

So calling withExecutor with an ExecutorService instance would give you a Function<Par<A>, Future<A>>, now to execute a Par and get a future we would call that function:

final ExecutorService s = ...
final Function<Par<A>, Future<A>> run = withExecutor(s);
final Par<A> par = ...
final Future<A> f = run.apply(par);

Note, this assumes Java 8.

Upvotes: 4

Synesso
Synesso

Reputation: 39018

This is known as type aliasing and is not present in Java. Though you might approximate it with something like:

abstract class Par<A> extends F<ExecutorService, Future<A>>

edit: I agree with Didier. It is a path to ruin.

Upvotes: 4

Related Questions