I'm used to declaring array inline like this:
String s1 = "world";
String[] strings = { "world" };
Why can't I do the same for functions? Given I have a class Book with getTitle() and getAuthor() methods, this is valid:
Function<Book, String> f1 = Book::getTitle;
System.out.println(f1.apply(myBook));
However this is not:
Function<Book, String>[] funcs = { Book::getTitle, Book::getAuthor };
for (Function<Book, String> f2 : funcs) {
System.out.println(f2.apply(myBook));
}
It doesn't like the inline array declaration and the compiler error is "Cannot create a generic array of Function"
Edit I'd argue my question isn't a duplicate of the suggestion as I want to statically define a set of functions using the array initializer syntax
Map<String, Function<Book, String>> mapToFunctions = new HashMap<>();funcs = new Function<Book, String>[] { Book::getTitle };Function[] funcs = { (Function<Book, String >) Book::getTitle };.List<String> titles = books.stream().map(Book::getTitle).collect(Collectors.toList());and thentitles.stream().forEach(System.out::println);to print them. It is redundant to create an array of the same function.