복붙노트

[SCALA] 자바 8 스칼라의 어느 동등한이 있습니까?

SCALA

자바 8 스칼라의 어느 동등한이 있습니까?

다만 java.util.Optional 자바 8 인 (다소) 스칼라의 옵션에 상응 [T] 타입 스칼라 하나에 상응가 [L은 R] 등?

해결법

  1. ==============================

    1.하나를 직접 만들거나 일부 타사 라이브러리를 사용할 필요가 그래서 어느 유형, 자바 8 없습니다 있습니다.

    하나를 직접 만들거나 일부 타사 라이브러리를 사용할 필요가 그래서 어느 유형, 자바 8 없습니다 있습니다.

    당신은 새로운 옵션 유형을 사용하여 이러한 기능을 구축 (하지만이 답변의 끝에 읽기) 할 수 있습니다 :

    final class Either<L,R>
    {
        public static <L,R> Either<L,R> left(L value) {
            return new Either<>(Optional.of(value), Optional.empty());
        }
        public static <L,R> Either<L,R> right(R value) {
            return new Either<>(Optional.empty(), Optional.of(value));
        }
        private final Optional<L> left;
        private final Optional<R> right;
        private Either(Optional<L> l, Optional<R> r) {
          left=l;
          right=r;
        }
        public <T> T map(
            Function<? super L, ? extends T> lFunc,
            Function<? super R, ? extends T> rFunc)
        {
            return left.<T>map(lFunc).orElseGet(()->right.map(rFunc).get());
        }
        public <T> Either<T,R> mapLeft(Function<? super L, ? extends T> lFunc)
        {
            return new Either<>(left.map(lFunc),right);
        }
        public <T> Either<L,T> mapRight(Function<? super R, ? extends T> rFunc)
        {
            return new Either<>(left, right.map(rFunc));
        }
        public void apply(Consumer<? super L> lFunc, Consumer<? super R> rFunc)
        {
            left.ifPresent(lFunc);
            right.ifPresent(rFunc);
        }
    }
    

    예 유스 케이스 :

    new Random().ints(20, 0, 2).mapToObj(i -> (Either<String,Integer>)(i==0?
      Either.left("left value (String)"):
      Either.right(42)))
    .forEach(either->either.apply(
      left ->{ System.out.println("received left value: "+left.substring(11));},
      right->{ System.out.println("received right value: 0x"+Integer.toHexString(right));}
    ));
    

    회고전에서 옵션 기반 솔루션은 권장되는 접근 방식은 더 학술 예처럼,하지만. 하나의 문제는 "하나"의 의미를 모순되는 "비어"에 null의 치료입니다.

    이 값이 null 인 경우에도, "중"엄격의 왼쪽 또는 오른쪽, 그래서 널 가능한 값을 고려 다음 코드를 보여주는 하나 :

    abstract class Either<L,R>
    {
        public static <L,R> Either<L,R> left(L value) {
            return new Either<L,R>() {
                @Override public <T> T map(Function<? super L, ? extends T> lFunc,
                                           Function<? super R, ? extends T> rFunc) {
                    return lFunc.apply(value);
                }
            };
        }
        public static <L,R> Either<L,R> right(R value) {
            return new Either<L,R>() {
                @Override public <T> T map(Function<? super L, ? extends T> lFunc,
                                           Function<? super R, ? extends T> rFunc) {
                    return rFunc.apply(value);
                }
    
            };
        }
        private Either() {}
        public abstract <T> T map(
          Function<? super L, ? extends T> lFunc, Function<? super R, ? extends T> rFunc);
    
        public <T> Either<T,R> mapLeft(Function<? super L, ? extends T> lFunc) {
            return this.<Either<T,R>>map(t -> left(lFunc.apply(t)), t -> (Either<T,R>)this);
        }
        public <T> Either<L,T> mapRight(Function<? super R, ? extends T> lFunc) {
            return this.<Either<L,T>>map(t -> (Either<L,T>)this, t -> right(lFunc.apply(t)));
        }
        public void apply(Consumer<? super L> lFunc, Consumer<? super R> rFunc) {
            map(consume(lFunc), consume(rFunc));
        }
        private <T> Function<T,Void> consume(Consumer<T> c) {
            return t -> { c.accept(t); return null; };
        }
    }
    

    그것은 단순히 두 팩토리 메소드의 시작 부분에 Objects.requireNonNull (값)을 삽입하여 널 (null)의 엄격한 거부에 그것을 쉽게 변경할 수 있습니다. 마찬가지로, 하나의 빈에 대한 지원을 추가하는 것은 상상할 수있을 것이다.

  2. ==============================

    2.골드 피처 푸가를 참조하십시오. 거기에 하나의 좋은 구현이있다.

    골드 피처 푸가를 참조하십시오. 거기에 하나의 좋은 구현이있다.

  3. ==============================

    3.글을 쓰는 시점에서, vavr (이전 javaslang는) 아마도 가장 인기있는 기능 자바 8 라이브러리입니다. 그것은 내 다른 대답 람다 동반자의 어느 꽤 유사하다.

    글을 쓰는 시점에서, vavr (이전 javaslang는) 아마도 가장 인기있는 기능 자바 8 라이브러리입니다. 그것은 내 다른 대답 람다 동반자의 어느 꽤 유사하다.

    Either<String,Integer> value = compute().right().map(i -> i * 2).toEither();
    
  4. ==============================

    4.자바 표준 라이브러리에는 어느 쪽이 없습니다. 그러나 다른 많은 좋은 클래스와 함께 FunctionalJava에서 하나의 구현이있다.

    자바 표준 라이브러리에는 어느 쪽이 없습니다. 그러나 다른 많은 좋은 클래스와 함께 FunctionalJava에서 하나의 구현이있다.

  5. ==============================

    5.외눈 박이는-반응은 '권리'이 Xor라는 하나의 구현을 바이어스했다.

    외눈 박이는-반응은 '권리'이 Xor라는 하나의 구현을 바이어스했다.

     Xor.primary("hello")
        .map(s->s+" world")
    
     //Primary["hello world"]
    
     Xor.secondary("hello")
        .map(s->s+" world")
    
     //Secondary["hello"]
    
     Xor.secondary("hello")
        .swap()
        .map(s->s+" world")
    
     //Primary["hello world"]
    
    Xor.accumulateSecondary(ListX.of(Xor.secondary("failed1"),
                                     Xor.secondary("failed2"),
                                     Xor.primary("success")),
                                     Semigroups.stringConcat)
    
    //failed1failed2
    

    양자 택일 또는 tuple2 역할을 할 수있는 관련 유형 Ior은도 있습니다.

  6. ==============================

    6.아니, 아무도 없다.

    아니, 아무도 없다.

    그들이 다른 언어로 같은 일을하는 동안 Java 언어 개발자 옵션 와 같은 유형이 임시 값으로 사용하기위한 것을 명시 적 상태 (는 예를 들어 스트림 작업 결과에) 그래서, 그들은 그들이 사용되지 않는 것으로 다른 언어로 사용된다. 그래서 (스트림 작업에서, 예를 들어) 자연적으로 발생하지 않기 때문에 어느 같은 것은 선택 사항이하는 것처럼이없는 것은 놀라운 일이 아니다.

  7. ==============================

    7.작은 도서관에서 하나의 독립적 인 구현이있다 "양가 감정"http://github.com/poetix/ambivalence

    작은 도서관에서 하나의 독립적 인 구현이있다 "양가 감정"http://github.com/poetix/ambivalence

    당신은 메이븐 중앙에서 그것을 얻을 수 있습니다 :

    <dependency>
        <groupId>com.codepoetics</groupId>
        <artifactId>ambivalence</artifactId>
        <version>0.2</version>
    </dependency>
    
  8. ==============================

    8.람다 동반자는 어느 유형이 (그리고 몇 가지 다른 유형의 기능은 예를 들어보십시오)

    람다 동반자는 어느 유형이 (그리고 몇 가지 다른 유형의 기능은 예를 들어보십시오)

    <dependency>
        <groupId>no.finn.lambda</groupId>
        <artifactId>lambda-companion</artifactId>
        <version>0.25</version>
    </dependency>
    

    그것을 사용하는 것은 쉽다 :

    final String myValue = Either.right("example").fold(failure -> handleFailure(failure), Function.identity())
    
  9. from https://stackoverflow.com/questions/26162407/is-there-an-equivalent-of-scalas-either-in-java-8 by cc-by-sa and MIT license