为什么java不能推断出这个类型?

问题描述 投票:0回答:1

我试图模仿java中的一些模式匹配行为:

interface Result<T>
{
    <U> U eliminate(Function<T, U> f, BiFunction<Integer, String, U> g);
}

record Success<T>(T value) implements Result<T>
{
    @Override public <U> U eliminate(Function<T, U> f, BiFunction<Integer, String, U> g)
    {
        return f.apply(value);
    }
}

record Failure<T>(int errCode, String message) implements Result<T>
{
    @Override public <U> U eliminate(Function<T, U> f, BiFunction<Integer, String, U> g)
    {
        return g.apply(errCode, message);
    }
}
public class Main
{
    public static void main(String[] args)
    {
        Result<Double> result = Result.success(4.0);

        var log = result.eliminate(
            value -> "Success: " + value,
            (code, message) -> "Failure: " + code + " " + message
        );

        System.out.println(log);
    }
}

上面的代码将编译并运行并输出“Success: 4.0”。 然而,当省略中间变量

log
并直接
println
它的定义时, 除非明确说明
eliminate
的返回类型,即
result.<String>eliminate(...)
, java突然不知道该怎么办了:

public class Main
{
    public static void main(String[] args)
    {
        Result<Double> result = Result.success(4.0);

        System.out.println(result.eliminate(
            value -> "Success: " + value,
            (code, message) -> "Failure: " + code + " " + message
        ));
    }
}
% javac -Xdiags:verbose Main.java
Main.java:7: error: reference to println is ambiguous
        System.out.println(result.eliminate(
                  ^
  both method println(char[]) in PrintStream and method println(String) in PrintStream match
Main.java:7: error: method println in class PrintStream cannot be applied to given types;
        System.out.println(result.eliminate(
                          ^
  required: char[]
  found:    String
  reason: argument mismatch; inference variable U has incompatible bounds
      upper bounds: char[],Object
      lower bounds: String
  where U,T are type-variables:
    U extends Object declared in method <U>eliminate(Function<T,U>,BiFunction<Integer,String,U>)
    T extends Object declared in interface Result
2 errors
java pattern-matching type-inference
1个回答
0
投票

因为您似乎正在返回“U”类型。我会切换你的“类型”并成功

interface Result<U>

record Success<U>(U value) implements Result<U>

或者直接完成

String
,因为这正是您想要返回的。

此外,从可读性的角度来看,我将创建一个“Response”类,将值映射到消息。如果您使用 Spring,则可以使用

ResponseEnity
。它使阅读更容易。

© www.soinside.com 2019 - 2024. All rights reserved.