1

In Kotlin, how do one instantiate a generic? In C# and Java this task is very simple and I feel really stupid for not being able to do this in any way I have tried.

Note that I have no control over the derivation of the "underlying" Kotlin generic and hence cannot use variance; that which I can however guarantee is that it is an instantiable Kotlin class (not Java) which does have a zero argument constructor.

Also note that I have read this already (without getting it to work): https://youtrack.jetbrains.com/issue/KT-6728

A bit of opinion - really really like Kotlin after a week or two's play.

C# Code / a very simple example. Java is very similar:

using System;

namespace GenInstance
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Console.WriteLine ("Hello World!");

            var w = new Instancer<Whatever> ().Map ();
            Console.WriteLine (w);
            Console.ReadLine ();
        }
    }

    public class Instancer<T> where T : new() {
        public T Map() {
            return new T();
        }
    }

    public class Whatever {
        public override string ToString ()
        {
            return "My Instance";
        }
    }
}
Kobi
  • 135,331
  • 41
  • 252
  • 292
user1210708
  • 513
  • 4
  • 11

0 Answers0