这个片段正在编译吗?我不这么认为 Java 14 条记录

Is this snippet compiling? I don't think so Java 14 records

周末我正在阅读一些关于 Java 14 个预览功能记录。我不想提出这个问题,因为这似乎是 Brian Goetz 的代码,我们都知道这个人是谁以及代表 Java 生态系统的是什么,但这一直在我脑海中浮现,我知道它将为我学习。

link 在这里。 https://www.infoq.com/articles/java-14-feature-spotlight/?utm_campaign=infoq_content&utm_source=infoq&utm_medium=feed&utm_term=Java

是这样的。

record PlayerScore(Player player, Score score) {
    // convenience constructor for use by Stream::map
    PlayerScore(Player player) { this(player, getScore(player)); }
}

List<Player> topN
    = players.stream()
             .map(PlayerScore::new)
             .sorted(Comparator.comparingInt(PlayerScore::score))
             .limit(N)
             .map(PlayerScore::player)
             .collect(toList());

我假设此行返回乐谱参考。

getScore(player)

也许你在我理解它试图做什么之前就已经看到它了,但有些事情我不明白。也许我错了。

这一行

.sorted(Comparator.comparingInt(PlayerScore::score))

comparingInt的API是这样的

public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) {

不过只要看懂了方法参考

PlayerScore::score

从 Records 元组返回 Score 引用对吗?不是整数或结果为整数

否则这会使代码编译我认为可能是输入错误。

record PlayerScore(Player player, int score) {
    // convenience constructor for use by Stream::map
    PlayerScore(Player player) { this(player, getScore(player)); }
}

根据我的理解,这段代码无法编译,正如我之前所说;也许我错了。

这可能无法编译的原因可能是因为 Score 是一种类型而不是 Integer 值。比较 record PlayerScoreScore 需要做的是确保两件事 -

  1. 使用Comparator.comparing

    List<Player> topN  = players.stream()
         .map(PlayerScore::new)
         .sorted(Comparator.comparing(PlayerScore::score)) //here
         .limit(N)
         .map(PlayerScore::player)
         .collect(toList());
    
  2. 确保 Score 实现 Comparable 例如:

    class Score implements Comparable<Score> {
        @Override
        public int compareTo(Score o) {
            return 0; // implementation
        }
    }
    

遗憾的是,我在链接文档中也没有看到您的 Score class 的实现,这是了解作者(或编辑)到底错过了什么的关键所在.例如,一个简单的 record 定义更改将使现有代码工作:

record PlayerScore(Player player, Integer score) { 
    // convenience constructor for use by Stream::map
    PlayerScore(Player player) {
        this(player, getScore(player));
    }
}

List<Player> topN = players.stream()
        .map(PlayerScore::new)
        .sorted(Comparator.comparingInt(PlayerScore::score))
        .limit(N)
        .map(PlayerScore::player)
        .collect(Collectors.toList());

只看一眼那部分,因为它与前面的例子是连续的,重要的是关联 getScore(Player player) 的 return 类型。

// notice the signature change
static int getScore(Player player) {
    return 0;
}