gpt4 book ai didi

java - 斯卡拉 2.12 : What is the equivalent of Java 8 method reference for universally quantified SAM trait?

转载 作者:搜寻专家 更新时间:2023-11-01 02:59:35 25 4
gpt4 key购买 nike

我的目标是通过新的 Scala 2.12 支持 SAM(单一抽象方法)特征来实现代数数据类型(教会编码)的单一值。

在 Java 中,以下程序返回 true :

import java.util.function.Function;
import java.util.function.Supplier;

@FunctionalInterface
public interface Maybe<A> {

<X> X fold(Supplier<X> empty, Function<A, X> just);

static <A, X> X empty0(Supplier<X> empty, Function<A, X> just) {
return empty.get();
}

static <A> Maybe<A> empty() {
return Maybe::empty0;
}

static void main(String[] args) {
Maybe<?> emptyString = Maybe.<String>empty();
Maybe<?> emptyInt = Maybe.<Integer>empty();

System.out.println(emptyString == emptyInt); // print "true".
}
}

我尝试将此编码移植到 scala 2.12,但它无法编译:

@FunctionalInterface
trait Maybe[A] {
def fold[X](empty: => X, just: A => X): X
}

object Maybe {
def empty0[A, X](empty: => X, just: A => X): X = empty

def empty[A]: Maybe[A] = empty0(_ ,_) // does not compile

def main(args: Array[String]): Unit = {
val emptyString: Maybe[String] = Maybe.empty
val emptyInt: Maybe[Integer] = Maybe.empty

print(emptyString eq emptyInt) // how to make this print "true"???
}
}

我得到的错误是: missing parameter type for expanded function ((x$1: <error>, x$2: <error>) => empty0(x$1, x$2))

我的目标是让 scalac 触发 Javac 完成的相同优化,使 java 程序打印“true”。只要不使用 asInstanceOf,我愿意接受满足 scalac 所需的任何东西。也不Nothing/方差注释。

编辑:由于目前不支持,我打开了一个 feature request on the scala issue tracker为此(请投票!;-)。

最佳答案

很遗憾,根据 the specification 不允许这样做:

It follows that:

  • if class C defines a constructor, it must be accessible and must define exactly one, empty, argument list;

  • m cannot be polymorphic;

  • it must be possible to derive a fully-defined type U from S by inferring any unknown type parameters of C.

关于java - 斯卡拉 2.12 : What is the equivalent of Java 8 method reference for universally quantified SAM trait?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39356644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com