欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

如何在 scala 中编写类似 BiConsumer 匿名函数的 java8 函数

最编程 2024-07-09 14:19:31
...

使用scala写出java的BiConsumer

最近做一个项目需要使用scala调用java的API,但是java的api上面的输入参数为BiComsumer接口,这种接口在java中写很简单,比如这样

(m,n)-> System.out.println(m+n)

但是在Scala中调用就没有那么简单了
于是我就查看了Biconsumer的源码,发现他有着两个方法,其中一个方法已经实现,我仅需实现一个accept方法即可。

package java.util.function;

import java.util.Objects;

/**
 * Represents an operation that accepts two input arguments and returns no
 * result.  This is the two-arity specialization of {@link Consumer}.
 * Unlike most other functional interfaces, {@code BiConsumer} is expected
 * to operate via side-effects.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #accept(Object, Object)}.
 *
 * @param <T> the type of the first argument to the operation
 * @param <U> the type of the second argument to the operation
 *
 * @see Consumer
 * @since 1.8
 */
@FunctionalInterface
public interface BiConsumer<T, U> {

    /**
     * Performs this operation on the given arguments.
     *
     * @param t the first input argument
     * @param u the second input argument
     */
    void accept(T t, U u);

    /**
     * Returns a composed {@code BiConsumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code BiConsumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after) {
        Objects.requireNonNull(after);

        return (l, r) -> {
            accept(l, r);
            after.accept(l, r);
        };
    }
}

于是我猜想,在java中可以这样做

        BiConsumer<Integer, Integer> a = new BiConsumer<Integer, Integer>() {

            @Override
            public void accept(Integer m, Integer n) {
                System.out.println(m+n);
            }
        };

        a.accept(3,8);

那么在scala中实现方式也就变得很清晰了

    val consumer = new BiConsumer[Integer, Integer](){
      override def accept(m:Integer, n:Integer]):Unit = {
         System.out.println(m + n);
      }
    }

于是这时候我就得到了consumer这个参数。问题得以解决

推荐阅读