【Java-Kotlin:泛型和方差】教程文章相关的互联网学习教程文章

java – Kotlin:泛型方法和for循环请求iterator()【代码】

这是一个简单的泛型方法,并且将forgs中的args传递给for循环会导致错误:for-loop range must have and iterator() methodfun main(args: Array<String>) {val arr: IntArray = intArrayOf(1,2,3,4)val charA: CharArray = charArrayOf('a','b','c','d')printMe(arr)printMe(charA)}fun <T>printMe(args: T){for (items in args){println(items)} }我如何让它迭代char []和数组的值解决方法:Kotlin中的for循环按惯例工作,静态地查找...

Java-Kotlin:泛型和方差【代码】

我想在Throwable上创建一个扩展函数,给定一个KClass,它以递归方式搜索与该参数匹配的根本原因.以下是一种可行的尝试:fun <T : Throwable> Throwable.getCauseIfAssignableFrom(e: KClass<T>): Throwable? = when {this::class.java.isAssignableFrom(e.java) -> thisnonNull(this.cause) -> this.cause?.getCauseIfAssignableFrom(e)else -> null }这也适用:fun Throwable.getCauseIfAssignableFrom(e: KClass<out Throwable>): ...

java – 仅限Consumer的kotlin泛型【代码】

让我们说这个java示例:interface Sink<T> {void accumulate(T t); }public static <T> void drainToSink(Collection<T> collection, Sink<? super T> sink) {collection.forEach(sink::accumulate); }注意第二个参数是如何声明的?超级T.我需要这个,因为我想调用这样的方法:Sink<Object> sink = .... // some Sink implementation Collection<String> strings = List.of("abc"); drainToSink(strings, sink);现在我想用kotlin(我...

Java to Kotlin泛型翻译【代码】

我想搬到Kotlin旧的Java项目,并发现有趣,无法将此转化为Kotlin而没有痛苦public interface BaseJView<P extends BaseJPresenter> {P createPresenter(); } public interface BaseJPresenter<V extends BaseJView> {void bindView(V view); }你能给出建议吗,我怎么能做到这一点?解决方法:一种方法是像这样使用recursive type definition:interface BaseJView<TSelf : BaseJView<TSelf, P>, P : BaseJPresenter<P, TSelf>> {fun cr...

java – kotlin错误的可空性推论没有任何泛型【代码】

在春天mvc(5.1.3)我试图做:val url : String? = null val matcher: ResultMatcher = MockMvcResultMatchers.forwardedUrl(url)我得到第二行的编译错误. 来自intellij(kotlinc-jvm 1.3.11):Error:(230, 56) Kotlin: Null can not be a value of a non-null type String或者从gradle(kotlin 1.2.71):Type mismatch: inferred type is String? but String was expectedspring方法的java源代码是:/*** Asserts the request was for...

kotlin 泛型 :out in

* in。它使得一个类型参数逆变:只可以被写入而不可以被读取(相当于Java中 ? super T) * out 声明处型变:我们可以标注Source 的参数类型T 来确保它仅从Source<T> 成员中返回(只读取,相当于Java中? extends T) out :只读 作者:中路杀神ai 链接:https://www.jianshu.com/p/826da76a6ff9 来源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。