Automatic type conversion in Java?

Is there a way to do automatic implicit type conversion in Java? For example, let's say I have two types: "FooSet" and "BarSet", which are set views. It is easy to convert between types, so I wrote two utility methods:

/** Given a BarSet, returns a FooSet */
public FooSet barTOfoo(BarSet input) { /* ... */ }

/** Given a FooSet, returns a BarSet */
public BarSet fooTObar(FooSet input) { /* ... */ }

Now tell me there is a method that I want to call:

public void doSomething(FooSet data) {
    /* .. */
}

But all I have is BarSet myBarSet... it means adding text, for example:

doSomething(barTOfoo(myBarSet));

Is there a way to tell the compiler that certain types can be automatically passed to other types? I know this is possible in C ++ with overload, but I cannot find a way in Java. I want to simply indicate:

doSomething(myBarSet);

And the compiler knows to automatically call barTOfoo()

+3
6

: ​​++, Java .

+5

, :

public void doSomething(FooSet data) {
    /* .. */
}

public void doSomething(BarSet data) {
    doSomething(barTOfoo(data));
}
+2

:

(1) , .

(2) hashCode override, - , Map , , ( ).

, , - . , ( ) . , , .

.

+1

, :

public void doSomething(FooSet data)
{
    /* .. */
}

public void doSomething(BarSet data)
{
    doSomething(barToFoo(data));
}

, (wikipedia) -.a >

, Java ( ), .

, , , java, , (java tutorial) .

0

( Scala ).

Variant :

/** Given a BarSet, returns a FooSet */
public Function<BarSet, FooSet> barTofoo = new Function<BarSet, FooSet>() {
    @Override public FooSet apply(BarSet input) { /* ... */ }
}

/** Given a FooSet, returns a BarSet */
public Function<FooSet, BarSet> fooToBar = new Function<FooSet, BarSet>() {
    @Override public BarSet apply(FooSet input) { /* ... */ }
}

/** Create a type conversion context in which both of these conversions are registered */
TypeConversionContext fooBarConversionContext = MatchingTypeConversionContext.builder()
    .register(FooSet.class, BarSet.class, fooToBar)
    .register(BarSet.class, FooSet.class, barToFoo)
    .build();

/** Put a FooSet into a Variant, bound to our type conversion context */
FooSet fooSet = new FooSet();
Variant data = Variant.of(fooSet).in(fooBarConversionContext);

/** Pull a BarSet out of the Variant */
public void doSomething(Variant data) {
    Preconditions.checkArgument(data.isConvertibleTo(BarSet.class);
    BarSet barSet = data.as(BarSet.class);
    // ...
}
0

Java . , . , . , , , .

-1

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


All Articles