Laurence Gonsalves
Laurence Gonsalves

Reputation: 143154

How does one specify type parameters to the primary constructor in Kotlin?

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

Answers (2)

yole
yole

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

Gary LO
Gary LO

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

Related Questions