Kotlin扩展功能按类型

什么是基于类型添加功能到类的惯用方式。 以下示例使用List作为类,并且Type参数<T>是列表中的对象的类。 比方说,你想要根据它们的类型用不同的比较器对这些列表进行排序。

 data class A(val foo: String) data class B(val bar: Int) private val aComparator: Comparator<A> = Comparator { lhs, rhs -> rhs.foo.compareTo(lhs.foo) } private val bComparator: Comparator<B> = Comparator { lhs, rhs -> rhs.bar.compareTo(lhs.bar) } fun <T: A> List<T>.sort(): List<T> { return this.sortedWith<T>(aComparator) } fun <T: B> List<T>.sort(): List<T> { return this.sortedWith<T>(bComparator) } 

这给出了一个错误,说明由于Java的重载规则,两个排序函数都具有相同的签名。 在Java中,我可能会给他们两个不同的可识别的名字,但是作为Kotlin扩展(egasortA()b.sortB())是相当难看的。 Kotlin不会显示sortA到一个List <B>,所以似乎有一个更好的方法来编写sort()来处理不同对象上的不同比较器。

这个例子很简单,但想象一下,如果我没有修改类A和B的权限,那么我就不能使用继承或者实现一个接口。 我也想过为每个班级添加一个比较,并使用任何? 但是这似乎也很麻烦。

一个答案似乎是:

 @JvmName("sortA") fun <T: A> List<T>.sort(): List<T> { return this.sortedWith<T>(aComparator) } @JvmName("sortB") fun <T: B> List<T>.sort(): List<T> { return this.sortedWith<T>(bComparator) } 

这似乎解决了Java的泛型擦除问题。

在这里找到: https : //kotlinlang.org/docs/reference/java-to-kotlin-interop.html

在这个网站上,我找到了这个解决方案

而不是这个

 fun Iterable<Long>.average(): Double {} fun Iterable<Int>.average(): Double {} 

使用platformName

 fun Iterable<Long>.average(): Long { } platformName("averageOfInt") fun Iterable<Int>.average(): Int { } 

编辑:这是弃用,而是使用JvmName。