为什么我们不能从私有扩展类型中获得公共类型?

如果我尝试这个:

sealed class Attributes data class Attributes1( val prop1: String ) : Attributes() private data class IMyType<A>( val attributes: A ) where A: Attributes typealias MyType1 = IMyType<Attributes1> 

…我得到的错误: '公共'typealias公开扩展类型IMyType'私人'

什么是为什么防止这个?

注意:使用Kotlin 1.1.4

编辑1

我明白什么是类型化的,我理解这些限制的含义。

我问的是为什么这些限制需要在那里。

如果你考虑我的示例代码…我希望MyType1 (也许是其他人)可以在这个文件之外访问,但是我不希望在这个文件之外使用原始/通用IMyType

这不是一个合法的用例吗?

根据定义, typealias是为现有类型提供一个替代名称。 所以你不能通过typealias提升现有类型的可见性。

从typealias的语法中,如果要在代码中使用typealias,则必须确保typealias的可见性低于或等于现有类型的可见性。 例如:

 internal class Bar private typealias PrivateFoo = Bar internal typealias InternalFoo = Bar //v--- error public typealias PublicFoo = Bar 

类型别名的可见性应该与相应的类型相同或更受限制。

当在文件中声明IMyTypeprivate时, IMyType是只能在该kotlin文件中访问的文件私有类。 如果您为IMyType声明公共类型别名MyType1 ,那么对于IMyType是私有的,因为MyType1可以在任何地方访问。 所以,这是被禁止的。

从Kotlin的文档 :

类型别名不会引入新的类型。 它们相当于相应的基础类型。 在代码中添加typealias Predicate<T>并使用Predicate<Int>时,Kotlin编译器始终将其展开为(Int) -> Boolean

具有typealias的主要目的是为现有类型提供替代名称。 在你的情况下, IMyTypeMyType1指向同一个类。 您不能通过文件外的MyType1访问IMyType ,因为IMyType意图是私有的。

不显示新类型的示例:

 //Kotlin code fun acceptMyType1(type: MyType1) {} //Decompiled code, MyType1 is not used public static final void acceptMyType1(@NotNull IMyType type) { Intrinsics.checkParameterIsNotNull(type, "type"); } 

侧面问题:你也不能通过公共子类暴露一个私有的超类 。