无法从函数<Short, Object> 转换为函数<Short, Short>

Cannot convert from Function<Short, Object> to Function<Short, Short>

所以,这个大学练习要求编写一个方法,将参数 a Function<Short, Short> 和结果类型 a Function<Short, Short> 作为参数。它应该 return 函数的结果除以 9。 这是我写的代码,虽然我非常有信心它应该可以工作,但 Eclipse 在第 16 行显示了一个我根本不理解的错误:

"Type mismatch: cannot convert from Function<Short,Object> to Function<Short,Short>. 

如果我把 Function<Integer, Integer> 放在两者中,或者如果我在 return 类型中写 Function<Short, Object> 并将参数保留为 Function,它会工作正常。

public Function<Short, Short> ulmic(Function<Short, Short> period) {
   return period.andThen(a -> a / 9);
}

为了让它工作,你必须这样写:

public Function<Short, Short> ulmic(Function<Short, Short> period) {
    return period.andThen(a -> (short) (a / 9));
}

当您应用操作数时,/ over a9,Java 将结果转换为整数。

Chapter 5. Conversions and Promotions可以读到:

One conversion context is the operand of a numeric operator such as + or *. The conversion process for such operands is called numeric promotion. Promotion is special in that, in the case of binary operators, the conversion chosen for one operand may depend in part on the type of the other operand expression.

5.6.2. Binary Numeric Promotion

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

  • If either operand is of type double, the other is converted to double.

  • Otherwise, if either operand is of type float, the other is converted to float.

  • Otherwise, if either operand is of type long, the other is converted to long.

  • Otherwise, both operands are converted to type int.