Understanding Mockito's Type Inference Trick in the mock() Method

Recently, I nearly misinterpreted code authored by a team member contrary to its intended purpose. The implementation initially appeared counterintuitive, prompting thorough reinvestigation documented herein. The team member’s code utilized generics for creating a method applicable to API invocations in a versatile manner. The explanation referenced employing an identical technique to Mockito library’s mock() method, warranting examination. Type Inference in Mockito’s mock() (Version: mockito-core 4.9 or higher, included in spring-boot-starter-test from 3.1 onwards) ...

January 19, 2025 · 729 words · Mihyang Gu

Generic Type Variance: Invariance, Covariance, and Contravariance

While working with Spring Batch, I encountered ItemWriter’s method void write(List<? extends T> var1) and pondered the rationale for such generic type specification. I have finally undertaken comprehensive investigation. Contravariance concepts proved conceptually challenging, requiring several hours to achieve comprehension. However, upon understanding, the underlying principles appear remarkably straightforward. This exposition attempts maximal clarity. Generic Terminology Initially, I had forgotten even the appropriate search terminology, necessitating terminological review. These terms follow Effective Java conventions. ...

November 7, 2021 · 796 words · Mihyang Gu