pio*_*rek 5 java spring kotlin
在春天mvc(5.1.3)我试图做:
val url : String? = null
val matcher: ResultMatcher = MockMvcResultMatchers.forwardedUrl(url)
Run Code Online (Sandbox Code Playgroud)
我得到第二行的编译错误.
来自intellij(kotlinc-jvm 1.3.11):
Error:(230, 56) Kotlin: Null can not be a value of a non-null type String
Run Code Online (Sandbox Code Playgroud)
或者从gradle(kotlin 1.2.71):
Type mismatch: inferred type is String? but String was expected
Run Code Online (Sandbox Code Playgroud)
spring方法的java源代码是:
/**
* Asserts the request was forwarded to the given URL.
* <p>This method accepts only exact matches.
* @param expectedUrl the exact URL expected
*/
public static ResultMatcher forwardedUrl(String expectedUrl) {
return result -> assertEquals("Forwarded URL", expectedUrl, result.getResponse().getForwardedUrl());
}
Run Code Online (Sandbox Code Playgroud)
intellij显示javadoc:
org.springframework.test.web.servlet.result.MockMvcResultMatchers @NotNull
@Contract(pure = true)
public static org.springframework.test.web.servlet.ResultMatcher forwardedUrl(@Nullable String expectedUrl)
Run Code Online (Sandbox Code Playgroud)
那么为什么编译器仍然需要非可空类型以及如何绕过该要求呢?
参数上没有明确的可空性注释MockMvcResultMatchers.forwardedUrl,因此它将默认为@NonNullApi,如下所示package-info.java:
/**
* Contains built-in {@code ResultMatcher} and {@code ResultHandler} implementations.
* <p>Use {@link org.springframework.test.web.servlet.result.MockMvcResultMatchers}
* and {@link org.springframework.test.web.servlet.result.MockMvcResultHandlers}
* to access instances of those implementations.
*/
@NonNullApi
@NonNullFields
package org.springframework.test.web.servlet.result;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
Run Code Online (Sandbox Code Playgroud)
有没有办法来形容空性在Java中,因此默认情况下同时传递String和String?成接受一个Java方法String是可行的.但是,Kotlin编译器尊重不同版本的可空性注释(例如javax.annotation.*,Android的注释,Spring的注释),以允许Java代码向Kotlin调用者提供可空性信息.
如何绕过这个?你不能.-你传递了错误类型的参数String,并String?在科特林是不同的类型.
| 归档时间: |
|
| 查看次数: |
170 次 |
| 最近记录: |