Reputation: 143154
In Java I can do something like this:
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();
}
}
Note that the Foo
class has no type parameters, but its constructor has type parameters. Can something equivalent be done in Kotlin?
Upvotes: 1
Views: 1332
Reputation: 97168
Kotlin does not support type parameters for constructors, so you can define a factory function instead:
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(""))
}
}
Upvotes: 3
Reputation: 1033
In Java
public class Bar<K,V> {
public final int x;
public Bar(Map<K, V> map) {
x = map.hashCode();
}
}
equivalent in Kotlin
class Bar <K,V> constructor (map: Map<K,V>) {
val x = map.hashCode()
}
In Java
public class Bar {
public final int x;
public Bar(Map map) {
x = map.hashCode();
}
}
equivalent in Kotlin
class Bar constructor (map: Map<*, *>) {
val x = map.hashCode()
}
In Java
public class Bar {
public final int x;
public <K, V>Bar(Map<K, V> map) {
x = map.hashCode();
}
}
equivalent in Kotlin
// no way to do so
According to Kotlin garmmer, there is no equivalent in implementation in Kotlin because we cannot define Type Parameters in primary nor secondary constructor.
Upvotes: 4