You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java编译错误:int无法转换为short的Lambda函数问题

解决Lambda表达式中int无法转换为Short的编译错误

你的代码里,value / 49 执行时会自动提升为int类型(Java整数运算默认以int为基础类型),但你定义的Function<Short, Short>要求返回Short类型,直接返回int值会触发类型不匹配的编译错误。

修复方法

1. 显式强制类型转换

把除法结果强制转为short,注意要保证结果在Short的取值范围(-32768 至 32767)内,避免溢出:

Function<Short, Short> div = (value) -> (short) (value / 49);

2. 用Short.valueOf()包装

通过Short.valueOf()将int结果转为Short对象,同样需要注意取值范围:

Function<Short, Short> div = (value) -> Short.valueOf((short) (value / 49));

完整修复代码

import java.util.function.Function;

public class Picnicker {
    public Function<Short, Short> rechafe(Function<Short, Short> sinkstone) {
        Function<Short, Short> div = (value) -> (short) (value / 49);
        Function<Short, Short> f = sinkstone.andThen(div);

        return f;
    }
}

内容的提问来源于stack exchange,提问作者Zinorux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 20:01:10