Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

functional programming - Why are there primitive functions like DoubleFunction in Java 8

I just had a look at the the new Java 8 function package and wonder why there are interfaces like

  • DoubleFunction
  • IntFunction
  • LongFunction
  • ...

which do not extend Function. Doesn't that mean I will not be able to pass a Function<T,Int> where a IntFunction<T> is required and vice versa? The same applies for *Block, *Supplier and *UnaryOperator.

I can see the advantage that I will not have to check for null when a primitive is returned, but the list of disadvantages seem to be much longer

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This issue is related to the fact that primitive types in Java are not unified to be substitutable for Object, and with generic type erasure.

Using Function<T, Integer> instead of IntFunction<T> when the last one suffices has 2 disadvantages:

  • Every returned int is boxed - meaning a larger memory footprint;
  • Every returned Integer gets an automatic runtime check (which can be optimized away, but yeah...);

Note that these kinds of issues with the collection framework in Java have led people to write a whole library, named Trove, that eschews the generic interfaces in favor of specialized collection types for every primitive type.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...