Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Higher kinded, open-type and wild card generics in Java, C#, Scala and C++

I'd been programming in C#, but was frustrated by the limitations of its type system. One of the first things, I learned about Scala was that Scala has higher kinded generics. But even after I'd looked at a number of articles, blog entries and questions I still wasn't sure what higher kinded generics were. Anyway I'd written some Scala code which compiled fine, Does this snippet use higher kinds?

abstract class Descrip [T <: DTypes, GeomT[_ <: DTypes] <: GeomBase[_]](newGeom: NewGeom[GeomT])
{
  type GeomType = GeomT[T]
  val geomM: GeomT[T] = newGeom.apply[T]()  
}

And then I thought maybe I'm already using higher kinded generics. As I understand it I was, but then as I now I understand it I had already been happily using higher kinded types in C# before I'd even heard of Scala. Does this snipet use higher kinded type?

namespace ConsoleApplication3
{
    class Class1<T>
    {
        List<List<T>> listlist;
    }
}

So to avert further confusion I thought it would be useful to clarify for each of Java, C# and Scala what they allow in terms of Higher kinded types, wild cards and the use of open / partially open types. As the key difference between C# and Scala seems to be that Scala allows wild cards and open types, where as C# has no wild card and requires all generic types to be closed before use. I know they are some what different but I think it would be useful to relate the existence of these features to their equivalent in C++ Templates.

So is the following correct? This table has been corrected for Alexey's answer

Lang:   Higher-kind Wild-card Open-types

Scala    yes         yes       yes

C#       no          no        no

Java     no          yes       no

C++      yes         yes       yes
like image 439
Rich Oliver Avatar asked May 24 '12 13:05

Rich Oliver


1 Answers

This is higher kinded type is it not:

No. A higher-kinded type is something like

class Class1<T>
{
    T<String> foo; // won't compile in actual C#
}

I.e. a generic type whose parameters are required to be generic themselves. Note that in this example Class1<IList> should compile, but Class1<String> or Class1<IDictionary> should not.

like image 127
Alexey Romanov Avatar answered Oct 24 '22 06:10

Alexey Romanov