如何在Kotlin的主要构造函数中指定类型参数?
在Java中,我可以这样做:
import java.util.List; import java.util.Map; class Foo { public final String s; // Parameters to constructor are generic, but constrained public <K> Foo(List<K> list, Map<K, String> map) { // Compute something from those parameters where result // has type independent of input type parameters. StringBuilder sb = new StringBuilder(); for (K k : list) { sb.append(map.get(k)); } s = sb.toString(); } }
请注意, Foo
类没有类型参数,但其构造函数具有类型参数。 Kotlin能做些什么吗?
Kotlin不支持构造函数的类型参数,所以你可以定义一个工厂函数:
class Foo private constructor(val s: String) { companion object { fun <K> create(list: List<K>, map: Map<K, String>) = Foo(list.map { map[it] }.joinToString("")) } }
在Java中
public class Bar<K,V> { public final int x; public Bar(Map<K, V> map) { x = map.hashCode(); } }
相当于Kotlin
class Bar <K,V> constructor (map: Map<K,V>) { val x = map.hashCode() }
在Java中
public class Bar { public final int x; public Bar(Map map) { x = map.hashCode(); } }
相当于Kotlin
class Bar constructor (map: Map<*, *>) { val x = map.hashCode() }
在Java中
public class Bar { public final int x; public <K, V>Bar(Map<K, V> map) { x = map.hashCode(); } }
相当于Kotlin
// no way to do so
根据Kotlin garmmer的说法 ,在Kotlin中没有相应的实现,因为我们无法在主要构造函数和次要构造函数中定义类型参数。