kotlin:typealias类型参数上的范围不允许

时间:2019-12-06 20:18:33

标签: generics kotlin

我正在尝试使用以下类型:


typealias Graph<T:Comparable<T>> = Map<T, List<T>>

我收到一条错误消息,指出在类型别名类型上不允许使用边界。

我该如何解决?

1 个答案:

答案 0 :(得分:1)

我不确定您要做什么,但是如果您想限制可以传递或存储在属性中的地图类型,这是我想到的最简单的方法。创建一个包装类,委托给地图,以便它可以是地图本身:

class Graph<T: Comparable<T>> (private val map: Map<T, List<T>>): Map<T, List<T>> by map {
    override fun toString() = map.toString()
    // You can use the IDE to generate equals and hashcode out of the map property
}

您还可以通过一些功能使用法变得熟悉:

fun <T:Comparable<T>> graphOf(): Graph<T> = Graph(emptyMap())
fun <T:Comparable<T>> graphOf(pair: Pair<T, List<T>>): Graph<T> = Graph(mapOf(pair))
fun <T:Comparable<T>> graphOf(vararg pairs: Pair<T, List<T>>): Graph<T> = Graph(mapOf(*pairs))

用法:

val graph: Graph<String> = graphOf("x" to listOf("y", "z"))

如果typealiasing可以做到,那么它就不如typealias好,因为您必须始终包装一个地图才能将其作为Graph传递。您还可以创建一个便捷函数,用于包装地图以作为参数传递时使用:

fun <T:Comparable<T>> Map<T, List<T>>.toGraph(): Graph<T> = 
        if (this is Graph) this else Graph(this)