public class ToDoubleFunctionTest {
public static void main(String[] args) {
1️⃣ ToDoubleFunction f = n -> n * 0.1;
2️⃣ double ans = f.applyAsDouble(20);
System.out.println(ans);
}
}
出力結果はどれでしょうか
- 20.0
- 20
- 1️⃣でコンパイルエラー
- 2️⃣でコンパイルエラー
- 実行時エラー
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
3: 1️⃣でコンパイルエラー
ToDoubleFunction<T>
は引数の型をジェネリクスで指定する必要があります。
戻り値の方はDouble
型になります。
問題では、ToDoubleFunction f = ・・・
とあり、引数の型を指定するジェネリクスがないためコンパイルエラーとなります。
以下のように修正するとコンパイルエラーは解消されます。
ToDoubleFunction<Integer> f = n -> n * 0.1;
もしくは引数の型もあらかじめ決まっているIntToDoubleFunction
が利用できます。
IntToDoubleFunction f = n -> n * 0.1;