Java: How to implement the interface? - java

What is the simplest and workable implementation of the interface of M. And how to implement method flatMap?
public interface M<T> {
<U> M<U> flatMap(Function<T, M<U>> f);
M<T> unit(T t);
}
I'm stuck in flatMap implementation.
M<String> m = new M<String>() {
#Override
public <U> M<U> flatMap(Function<String, M<U>> f) {
return null; // ?
}
#Override
public M<String> unit(String s) {
return new M<String>() {
#Override
public <U> M<U> flatMap(Function<String, M<U>> f) {
return null; // ?
}
#Override
public M<String> unit(String s) {
return null; // ?
}
};
}
};

Related

Call a method after my class execution is complete

I made a class which it execute step by step with or without delay some functions for a amateur game which i develop. The problem is that i want to create an overriden method which is called upon finish like the exactly i give bellow:
I want to call like that:
EventQueueExecutorBuilder.of(player).after(Duration.ofSeconds(5)).apply(s -> s.setName("stackoverflow")).GET() ->
{
#Override
public void onFinish()
{
System.out.println("Execution complete!");
}
}
Basically this wait for 5 second, set the player name to "Stackoverflow" and then print out "Execution complete".
I don't know what i need to change to make overriden method like the example i gave. Here's my full code:
public class EventQueueExecutorBuilder<T> implements Runnable
{
private final T _element;
private final List<QueueExecutor> _holder = new CopyOnWriteArrayList<>();
public EventQueueExecutorBuilder(final T element)
{
_element = element;
}
public EventQueueExecutorBuilder<T> applyIf(final Predicate<T> predicate, final Consumer<T> consume)
{
if (!Util.isAnyNull(_element, predicate, consume))
{
_holder.add(new QueueExecutor(() -> Util.ifThenConsume(_element, predicate, consume), Duration.ZERO));
}
return this;
}
public EventQueueExecutorBuilder<T> apply(final Consumer<T> consume)
{
if (!Util.isAnyNull(_element, consume))
{
_holder.add(new QueueExecutor(() -> consume.accept(_element), Duration.ZERO));
}
return this;
}
public EventQueueExecutorBuilder<T> after(final Duration duration)
{
if (!Util.isAnyNull(_element, duration))
{
_holder.add(new QueueExecutor(null, duration));
}
return this;
}
public EventQueueExecutorBuilder<T> GET()
{
ThreadPoolManager.getInstance().executeEvent(this);
return this;
}
public void onFinish()
{
}
#Override
public void run()
{
if (_holder.isEmpty())
{
return;
}
final QueueExecutor executor = _holder.remove(0);
if (!executor.getDuration().isZero())
{
ThreadPoolManager.getInstance().scheduleEvent(this, executor.getDuration().toMillis());
}
else
{
executor.getTask().run();
}
}
public static <T> EventQueueExecutorBuilder<T> of(final T element)
{
return new EventQueueExecutorBuilder<>(element);
}
//#formatter:off
private static record QueueExecutor (Runnable getTask, Duration getDuration) {}
//#formatter:on
}

How I can convert this Generic Class to a Parcelable?

I want to convert this generic class to a parcelable object, but I don't have very clear the concepts of the issue.
Class:
public class Type<T> implements Parcelable {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
This is what I've tried,. but I know that this is not correct, or maybe this is not complete.
public class Type<T> implements Parcelable {
// T stands for "Type"
private T t;
protected Type(Parcel in) {
}
public void set(T t) { this.t = t; }
public T get() { return t; }
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
public static final Creator< Type > CREATOR = new Creator< Type >() {
#Override
public Type createFromParcel(Parcel in) {
return new Type(in);
}
#Override
public Type[] newArray(int size) {
return new Type[size];
}
};
}
This is similar approach as vikas kumar but guarantte that you can pass only Parcelable as T parameter so you avoid exception.
public class Type<T extends Parcelable> implements Parcelable {
private T t;
protected Type(Parcel in) {
t = (T) in.readValue(t.getClass().getClassLoader());
}
public static final Creator<Type> CREATOR = new Creator<Type>() {
#Override
public Type createFromParcel(Parcel in) {
return new Type(in);
}
#Override
public Type[] newArray(int size) {
return new Type[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(t);
}
}
Your generic data type may cause runtime error
so make sure you implements Parcelable and also the class you are passing should implement Parcelable otherwise it will cause runtime error.
public class Type<T extends Parcelable> implements Parcelable {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
protected Type(Parcel in) {
final String className = in.readString();
try {
t = in.readParcelable(Class.forName(className).getClassLoader());
} catch (ClassNotFoundException e) {
Log.e("readParcelable", className, e);
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(t);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Type> CREATOR = new Parcelable.Creator<Type>() {
#Override
public Type createFromParcel(Parcel in) {
return new Type(in);
}
#Override
public Type[] newArray(int size) {
return new Type[size];
}
};
}

Implementing a kotlin interface in java

So, after this question where I basically exploits reflection for passing primitive references to modify the primitive itself, like:
_begin("Another Window", ::showAnotherWindow)
I was looking for something to make something similar possible also from java, where at the moment I am using plains primitive arrays:
private boolean[] showAnotherWindow = {false};
imgui.begin("Another Window", showAnotherWindow);
#hotkey suggested me the possibility to create a class implementing the KMutableProperty0 interface and that automatically gets and sets the corresponding variable
Example:
KMutableProperty0<Boolean> prop =
PropUtils.javaProp(this, t -> t.showAnotherWindow, (t, r) -> { t.showAnotherWindow = r; });
_begin("Another Window", prop);
So, I wanted to give it a try and implemented the following in java.
Getter:
#FunctionalInterface
public interface Getter<T> {
T get();
}
Setter:
#FunctionalInterface
public interface Setter<T> {
void set(T type);
}
And then the class itself (I just wrote the constructor, all the methods are those requested by the interface and automatically implemented by the IDE) :
public class JavaProp <T> implements KMutableProperty0<T> {
private imgui.Getter<T> getter;
private imgui.Setter<T> setter;
public JavaProp(imgui.Getter<T> getter, imgui.Setter<T> setter) {
this.getter = getter;
this.setter = setter;
}
#Override
public void set(T t) {
setter.set(t);
}
#NotNull
#Override
public Setter<T> getSetter() {
return null;
}
#Override
public T get() {
return getter.get();
}
#Nullable
#Override
public Object getDelegate() {
return null;
}
#NotNull
#Override
public Getter<T> getGetter() {
return null;
}
#Override
public T invoke() {
return null;
}
#Override
public boolean isLateinit() {
return false;
}
#Override
public boolean isConst() {
return false;
}
#NotNull
#Override
public String getName() {
return null;
}
#NotNull
#Override
public List<KParameter> getParameters() {
return null;
}
#NotNull
#Override
public KType getReturnType() {
return null;
}
#NotNull
#Override
public List<KTypeParameter> getTypeParameters() {
return null;
}
#Override
public T call(Object... objects) {
return null;
}
#Override
public T callBy(Map<KParameter, ?> map) {
return null;
}
#Nullable
#Override
public KVisibility getVisibility() {
return null;
}
#Override
public boolean isFinal() {
return false;
}
#Override
public boolean isOpen() {
return false;
}
#Override
public boolean isAbstract() {
return false;
}
#NotNull
#Override
public List<Annotation> getAnnotations() {
return null;
}
}
But whenever I try to run that, I get the following:
Error:(45, 12) java: reference to Getter is ambiguous
both interface kotlin.reflect.KProperty0.Getter in kotlin.reflect.KProperty0 and interface kotlin.reflect.KProperty.Getter in kotlin.reflect.KProperty match
The problematic function is this one:
#NotNull
#Override
public Getter<T> getGetter() {
return null;
}
And the relevant file is kotlin.reflect.KProperty.tk, you can find it here
Any idea how could I solve it?
Just specify which interface you mean:
public KProperty0.Getter<T> getGetter()
But I would prefer to implement the class in Kotlin and only consume it from Java.

java - Return a value from Visitor

Suppose we have following classes which we can't change:
interface Base {
void accept(Visitor visitor);
}
class Foo implements Base {
short getShortValue() {
return 1;
}
#Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
class Bar implements Base {
int getIntValue() {
return 2;
}
#Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
interface Visitor {
void visit(Foo foo);
void visit(Bar bar);
}
And we need to implement method:
int getValue(Base base)
There are many possibilities to do it with visitor using some storage object:
int useArray(Base base) {
int[] result = new int[1];
base.accept(new Visitor() {
#Override
public void visit(Foo foo) {
result[0] = foo.getShortValue();
}
#Override
public void visit(Bar bar) {
result[0] = bar.getIntValue();
}
});
return result[0];
}
int useAtomic(Base base) {
AtomicInteger result = new AtomicInteger();
base.accept(new Visitor() {
#Override
public void visit(Foo foo) {
result.set(foo.getShortValue());
}
#Override
public void visit(Bar bar) {
result.set(bar.getIntValue());
}
});
return result.intValue();
}
int useMutable(Base base) {
MutableInteger result = new MutableInteger(0);
base.accept(new Visitor() {
#Override
public void visit(Foo foo) {
result.setValue(foo.getShortValue());
}
#Override
public void visit(Bar bar) {
result.setValue(bar.getIntValue());
}
});
return result.getValue();
}
Or something perverted:
int useException(Base base) {
class GotResult extends RuntimeException {
private final int value;
public GotResult(int value) {
this.value = value;
}
}
try {
base.accept(new Visitor() {
#Override
public void visit(Foo foo) {
throw new GotResult(foo.getShortValue());
}
#Override
public void visit(Bar bar) {
throw new GotResult(bar.getIntValue());
}
});
} catch (GotResult result) {
return result.value;
}
throw new IllegalStateException();
}
Or don't use visitor at all:
int useCast(Base base) {
if (base instanceof Foo) {
return ((Foo) base).getShortValue();
}
if (base instanceof Bar) {
return ((Bar) base).getIntValue();
}
throw new IllegalStateException();
}
Are these our only options now? We have Java 8 (will have 9 soon enough) and still writing these ugly pieces of error-prone code. :)
I agree that not being able to return a value from the visitor is terrible from a safe usage point of view.
To avoid the burden of the gymnastic you demonstrated above, your best option is to create a wrapper type that expose a sane API (based on the corrected visitor pattern) so that the dirty work is done only once: when converting a Base value to that wrapper type.
Here is how you could do it:
interface BaseW {
interface Cases<X> {
X foo(Foo foo);
X bar(Bar bar);
}
<X> X match(Cases<X> cases);
//or alternatively, use a church encoding:
//<X> X match(Function<Foo, X> foo, Function<Bar, X> bar);
default Base asBase() {
return match(new Cases<Base>() {
#Override
public Base foo(Foo foo) {
return foo;
}
#Override
public Base bar(Bar bar) {
return bar;
}
});
}
static BaseW fromBase(Base base) {
return new Visitor() {
BaseW baseW;
{
base.accept(this);
}
#Override
public void visit(Foo foo) {
baseW = new BaseW() {
#Override
public <X> X match(Cases<X> cases) {
return cases.foo(foo);
}
};
}
#Override
public void visit(Bar bar) {
baseW = new BaseW() {
#Override
public <X> X match(Cases<X> cases) {
return cases.bar(bar);
}
};
}
}.baseW;
}
static int useCorrectedVisitor(Base base) {
return fromBase(base).match(new Cases<Integer>() {
#Override
public Integer foo(Foo foo) {
return (int) foo.getShortValue();
}
#Override
public Integer bar(Bar bar) {
return bar.getIntValue();
}
});
// or, if church encoding was used:
// return fromBase(base).match(
// foo -> (int) foo.getShortValue(),
// bar -> bar.getIntValue()
// );
}
}
Now (shameless plug), if you don't mind using derive4j (a jsr 269 code generator) the above can be simplified a fair bit, as well as improving syntax:
#org.derive4j.Data // <- generate an BaseWs classe that allows handling
// of the interface as an algebraic data type.
interface BaseW {
interface Cases<X> {
X foo(Foo foo);
X bar(Bar bar);
}
<X> X match(Cases<X> cases);
default Base asBase() {
return match(BaseWs.cases(f -> f, b -> b));
}
static BaseW fromBase(Base base) {
return new Visitor() {
BaseW baseW;
{
base.accept(this);
}
#Override
public void visit(Foo foo) {
baseW = BaseWs.foo(foo);
}
#Override
public void visit(Bar bar) {
baseW = BaseWs.bar(bar);
}
}.baseW;
}
static int useStructuralPatternMatching(Base base) {
return BaseWs.caseOf(fromBase(base))
.foo(foo -> (int) foo.getShortValue())
.bar(Bar::getIntValue);
}
}
Actually you can take advantage of Java's generics:
interface Visitor<T> {
T visit(Foo foo);
T visit(Bar bar);
}
interface Base {
<T> T accept(Visitor<T> visitor);
}
interface Foo extends Base {
}
interface Bar extends Base {
}
public final class VisitorExample {
static class ConcreteFoo implements Foo {
#Override
public <T> T accept(Visitor<T> visitor) {
return visitor.visit(this);
}
}
static class ConcreteBar implements Bar {
#Override
public <T> T accept(Visitor<T> visitor) {
return visitor.visit(this);
}
}
static class ClassNameExtractor implements Visitor<String> {
#Override
public String visit(Foo foo) {
return foo.getClass().getName();
}
#Override
public String visit(Bar bar) {
return bar.getClass().getName();
}
}
public static void main(String[] args) {
Visitor<String> visitor = new ClassNameExtractor();
Foo foo = new ConcreteFoo();
Bar bar = new ConcreteBar();
final String stringResultFromFoo = foo.accept(visitor);
System.out.println(stringResultFromFoo);
final String stringResultFromBar = bar.accept(visitor);
System.out.println(stringResultFromBar);
}
}
By declaring the accept() method to return <T> T, you can control the return type by using a generic vistor Visitor<T>. So you can return anything but primitive types.
The downside of this approach is that if you do not want to return anything, your concrete visitor will have to be of type Visitor<Void> and it has to have an annoying return null on the visit() methods.
You can also use a member variable in the Visitor:
class VisitorSupplier {
Integer result;
#Override
public void visit(Foo foo) {
result.set(foo.getShortValue());
}
#Override
public void visit(Bar bar) {
result.set(bar.getIntValue());
}
public Integer get() {
return result;
}
}
and use as:
VisitorSupplier visitorSupplier = new VisitorSupplier();
bar.accept(visitorSupplier);
return visitorSupplier.get();
If you can modify the classes that you visit, or maybe extend, you could add a template method like:
public <T, U extends Visitor & java.util.function.Supplier<T>> T acceptSupplier(
final #NotNull U visitorSupplier
)
{
accept(visitorSupplier);
return visitorSupplier.get();
}
make your visitor to implement Supplier (with the get method that I already provided):
class VisitorSupplier implements java.util.function.Supplier<Integer> { ...
and use more elegantly as:
return bar.acceptSupplier(new VisitorSupplier());
If instead of generic names, based on patterns, you use something more business specific, you can get quite readable code like:
Statistics getStatistics() {
return data.transform(new StatisticsSupplier());
}

Is it possible to point to anonymous class by .THIS keyword?

SSCCE:
public class Test {
public Test() {
new Anonymous1() {
void validate() {
new Anonymous2() {
int calculate() {
return Math.abs(Anonymous1.this.getValue()); // compilation error - Anonymous1 is not an enclosing class
}
};
}
};
}
}
abstract class Anonymous1 {
abstract void validate();
int getValue() {
return 0;
}
}
abstract class Anonymous2 {
abstract int calculate();
}
I know that it looks complicated and unusable, but I am just wonder is it possible to point to Anonymous1 class from Anonymous2 using .this pointer, or in any else way.
You need to do it in the class.
public Test() {
new Anonymous1() {
void validate() {
final Object this1 = this;
new Anonymous2() {
int calculate() {
return Math.abs(this1.getValue());
}
}
}
}
}
or even better, extract the things you need first and use effectively final added in Java 8.
public Test() {
new Anonymous1() {
void validate() {
int value = getValue();
new Anonymous2() {
int calculate() {
return Math.abs(value);
}
}
}
}
}
if Anonymous1 and Anonymous2 were interfaces you could use lambdas in Java 8.
public Test() {
Anonymous1 a = () -> {
int v = getValue();
Anonymous2 = a2 = () -> Math.abs(v);
};
}

Categories

Resources