- Functional Programming with Java Tutorial
- Home
- Overview
- Aspects
- Functions
- Functional Composition
- Eager vs Lazy Evaluation
- Persistent Data Structure
- Recursion
- Parallelism
- Optionals & Monads
- Closure
- Currying
- Reducing
- Java 8 Onwards
- Lambda Expressions
- Default Methods
- Functional Interfaces
- Method References
- Constructor References
- Collections
- Functional Programming
- High Order Functions
- Returning a Function
- First Class Functions
- Pure Functions
- Type Inference
- Exception Handling in Lambda Expressions
- Streams
- Intermediate Methods
- Terminal methods
- Infinite Streams
- Fixed Length Streams
- Useful Resources
- Quick Guide
- Resources
- Discussion
Functional Programming - Type Inference
Type inference is a technique by which a compiler automatically deduces the type of a parameter passed or of return type of a method. Java 8 onwards, Lambda expression uses type inference prominently.
See the example below for clarification on type inference.
Example- Type Inference
public class FunctionTester { public static void main(String[] args) { Join<Integer,Integer,Integer> sum = (a,b) -> a + b; System.out.println(sum.compute(10,20)); Join<String, String, String> concat = (a,b) -> a + b; System.out.println(concat.compute("Hello ","World!")); } interface Join<K,V,R>{ R compute(K k ,V v); } }
Output
30 Hello World!
A lambda expression treats each parameter and its return type as Object initially and then inferred the data type accordingly. In first case, the type inferred is Integer and in second case type inferred is String.
Advertisements