1

i'm trying to convert this c# class to kotlin for android:

public class ChildItemCollection<P, T, C> : ICollection<T>
    where P : class
    where T : ChildItem<P>
    where C : class, ICollection<T>
{

    private P _parent;
    private C _collection;

    public ChildItemCollection(P parent, C collection)
    {
        this._parent = parent;
        this._collection = collection;
    }


...

}

public class ChildItemCollection<P, T> : ChildItemCollection<P, T, List<T>>
        where P : class
        where T : ChildItem<P>
    {
        #region Constructors
        public ChildItemCollection(P parent)
            : base(parent, new List<T>()) { }

        public ChildItemCollection(P parent, ICollection<T> collection)
            : this(parent)
        {
            foreach (T item in collection)
                this.Add(item);
        }
        #endregion Constructors
    }

I have tried many things without success.

I didn't understand how to use the "where" lines either.

SWAppDev
  • 248
  • 1
  • 3
  • 13
  • Define 'without success'. – nhaarman Jun 06 '17 at 14:25
  • `where P : class` looks wrong, `class` is a keyword. Take a look at the last code example: https://kotlinlang.org/docs/reference/generics.html#upper-bounds – Miha_x64 Jun 06 '17 at 15:09
  • Please provide the exact compilation error in your questions (this is probably why all the down votes happened) – voddan Jun 07 '17 at 06:02
  • @Miha_x64 `where P : class` is a perfectly valid constraint. It requires the generic parameter to be a reference type, so for example `string` or `List` would work while `int` wouldn't. The opposite also exists, `where P : struct`, which requires it to be a value type. – Nyde Dec 09 '22 at 09:41

1 Answers1

10

In Kotlin, you can specify the type parameter upper bounds at their declaration:

class ChildItemCollection<P, T : ChildItem<P>, C : Collection<T>> : ...

If you have multiple upper bounds, they should be specified separately with where, see another Q&A.

Also, Kotlin does not have a class upper bound, because there's no distinction between value types and classes.

hotkey
  • 140,743
  • 39
  • 371
  • 326