我是Kotlin 的新手,正在try 用这种语言写一些项目.

'public' function exposes its 'public/*package*/' return type argument FooSettings

I understand the problem is but I am not sure how to fix it in Kotlin since I am still trying get familiar with Kotlin. I can see that Kotlin is being smart and only trying to return of type that extends FooSettings. However the problem is FooSettings is package public only which means that I cannot access if in my Kotlin project.

我做了一些关于Kotlin泛型和使用inout的研究,但是我无法解决这个问题.

在我的Kotlin项目中,我能做些什么来修复我看到的错误吗?

代码片段

This is sample of Java library class:个 注意,我没有办法更改库的实现.我必须使用这个图书馆,并将其扩展到Kotlin .

对我来说,java库是以这种方式编写的,并期望它被重写,这似乎很奇怪,但这是另一天的问题.

import java.util.Collections;
import java.util.List;

public abstract class ClassA {
    public List<FooBuilder<?>> getBuilder(Foo foo) {
        return Collections.emptyList();
    }
}

public class Foo {
}

public abstract class FooBuilder<U extends FooBuilder.FooSettings> {
    // implementation of Class
    abstract static class FooSettings {
        // implementation of Class
    }
}

Normally Java classes would override the method like such:

import java.util.List;

public class MyJavaClassA extends ClassA {
    @Override public List<FooBuilder<?>> getBuilder(final Foo foo) {
        // implementation
    }
}

But I am trying to write in Kotlin such that it looks like:提醒一下,这个Kotlin依赖于Java库,并且没有访问包公共类的权限.

class MyKotlinClassA : ClassA() {
    override fun getBuilder(foo: Foo): MutableList<FooBuilder<*>> {
        // implementation
    }
}

This causes error

'public' function exposes its 'public/*package*/' return type argument FooSettings

推荐答案

我猜你说的"公共包裹"是指"私有包裹"?在您的示例中,FooBuilder.FooSettings没有可见性修饰符,因此使用Java默认的package private.假设这就是你的意思...

您将能够在Kotlin代码中访问包私有类FooSettings,但前提是您将该Kotlin代码放入与声明FooSettings的包匹配的包中.

您仍然会得到相同的编译错误,但这并不是因为您无法访问该类型:而是因为您试图在比该类型的声明更可见的上下文中使用它.i、 e.您试图获取包私有类型,并将其用作公共方法签名的一部分,这是不允许的.为了解决这个问题,你需要给你的Kotlin 班级打internal分.

值得一提的是,对于Kotlin 来说,internal意味着它在module中可见,而不是在package中.这些都被详细解释了here.

Kotlin相关问答推荐

在Kotlin中可以连接两个范围吗?

如何进行基于lambda/谓词的两个列表的交集?

哪个更好? Integer.valueOf(readLine()) 或 readLine()!!.toInt()

为什么 trySend 会发出假数据?

Kotlin 启动与启动(Dispatchers.Default)

使用事务时未调用 Kafka ConsumerInterceptor onCommit

通用接口继承

Kotlin:伴随对象内的函数扩展

奇怪的 cotlin check Not Null 参数错误

如何在 kotlin 中通过反射设置委托属性值?

如何使用 Findbugs 避免 kotlin 文件

在协程中等待侦听器内的数据

如何在主线程上使用 Kotlin 协程 await()

Kotlin 类的调用方法

Kotlin Compose,在行中对齐元素

使用主构造函数时使用Kotlin getter/setter

Android Jetpack导航,另一个主机片段中的主机片段

修改扩展函数中的this

保存对象时未填充 Spring Boot JPA@CreatedDate @LastModifiedDate

将 Double 转换为 ByteArray 或 Array Kotlin