0
0

Java gold 例題 Function

Last updated at Posted at 2024-08-07
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);
	}
}

出力結果はどれでしょうか

  1. 20.0
  2. 20
  3. 1️⃣でコンパイルエラー
  4. 2️⃣でコンパイルエラー
  5. 実行時エラー

3: 1️⃣でコンパイルエラー

ToDoubleFunction<T>は引数の型をジェネリクスで指定する必要があります。
戻り値の方はDouble型になります。
問題では、ToDoubleFunction f = ・・・とあり、引数の型を指定するジェネリクスがないためコンパイルエラーとなります。
以下のように修正するとコンパイルエラーは解消されます。

ToDoubleFunction<Integer> f = n -> n * 0.1;

もしくは引数の型もあらかじめ決まっているIntToDoubleFunctionが利用できます。

IntToDoubleFunction f = n -> n * 0.1;

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0