Hello! I have problem with Kotlin type inference. ...
# announcements
a
Hello! I have problem with Kotlin type inference. Please help me solve it if it possible.
The problem in the Spring framework. Let me show the Java code example first:
Copy code
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

@ExtendWith(SpringExtension.class)
@SpringBootTest
public class SpringJavaConfiguration {

    private MockMvc mockMvc;
    @Autowired
    private WebApplicationContext context;

    @BeforeEach
    void setUp() {
        mockMvc = webAppContextSetup(context)
                          .apply(springSecurity())
                          .build();
    }
}
Then I try to do same on Kotlin
Copy code
import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity
import org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup

@ExtendWith(SpringExtension::class)
@SpringBootTest
class SpringKotlinConfiguration {

    private var mockMvc: MockMvc? = null
    @Autowired
    lateinit var context: WebApplicationContext

    @BeforeEach
    internal fun setUp() {
        mockMvc = webAppContextSetup(context)
            .apply(springSecurity()) // cannot inference type here
            .build()
    }
}
As you can see result of call method apply cannot be inferred. Signatures of class and method
apply
present below
Copy code
public abstract class AbstractMockMvcBuilder<B extends AbstractMockMvcBuilder<B>>
		extends MockMvcBuilderSupport implements ConfigurableMockMvcBuilder<B> {
    public final <T extends B> T apply(MockMvcConfigurer configurer) {
    //method code
    }
And I cannot specify type myself because it is cyclic dependency on itself either suppress it. You can find source code here: https://github.com/artglorin/kotlin-type-inference-failure
r
Can you screenshot the actual error in your IDE ?
a
of course
h
Spring is just ensuring to return the type of the builder. Since
webAppContextSetup(…)
returns a
DefaultMockMvcBuilder
, I'd just use that here.
i.e., use
apply<DefaultMockMvcBuilder>(springSecurity())
✔️ 2
a
Thanks! I have been resolving it so much time. But I have looked in wrong direction 🙂