All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.aol.cyclops.vavr.adapter.TryAdapter Maven / Gradle / Ivy

package com.aol.cyclops.vavr.adapter;


import com.aol.cyclops2.types.anyM.AnyMValue;
import com.aol.cyclops2.types.extensability.ValueAdapter;
import cyclops.conversion.vavr.FromCyclopsReact;
import cyclops.conversion.vavr.ToCyclopsReact;
import cyclops.monads.Vavr;
import cyclops.monads.VavrWitness;
import cyclops.monads.VavrWitness.tryType;
import com.aol.cyclops2.types.extensability.AbstractFunctionalAdapter;
import cyclops.control.Maybe;
import cyclops.monads.AnyM;
import io.vavr.control.Try;
import lombok.AllArgsConstructor;

import java.util.function.Function;
import java.util.function.Predicate;


@AllArgsConstructor
public class TryAdapter implements ValueAdapter {

    public  T get(AnyMValue t){
         return tryType(t).get();
    }

    @Override
    public  Iterable toIterable(AnyM t) {
        return Maybe.fromIterable(t.unwrap());
    }

    @Override
    public  AnyM ap(AnyM> fn, AnyM apply) {
        try {
            Try f = tryType(apply);
            Try> fnF = tryType(fn);
            Try res = FromCyclopsReact.toTry(ToCyclopsReact.toTry(fnF).combine(ToCyclopsReact.toTry(f), (a, b) -> a.apply(b)));
            return Vavr.tryM(res);
        }catch(Throwable t){
            return Vavr.tryM(Try.failure(t));
        }

    }

    @Override
    public  AnyM filter(AnyM t, Predicate fn) {
        return Vavr.tryM(tryType(t).filter(fn));
    }

     Try tryType(AnyM anyM){
        return anyM.unwrap();
    }

    @Override
    public  AnyM empty() {
        return Vavr.tryM(Try.failure(null));
    }



    @Override
    public  AnyM flatMap(AnyM t,
                                     Function> fn) {
        return Vavr.tryM(tryType(t).flatMap(fn.andThen(a-> tryType(a))));

    }

    @Override
    public  AnyM unitIterable(Iterable it)  {
        return Vavr.tryM(FromCyclopsReact.toTry(cyclops.control.Try.fromIterable(it)));
    }

    @Override
    public  AnyM unit(T o) {
        return Vavr.tryM(Try.success(o));
    }

    @Override
    public  AnyM map(AnyM t, Function fn) {
        return Vavr.tryM(tryType(t).map(fn));
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy