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.

4
  • Define 'without success'. Commented Jun 6, 2017 at 14:25
  • where P : class looks wrong, class is a keyword. Take a look at the last code example: kotlinlang.org/docs/reference/generics.html#upper-bounds Commented Jun 6, 2017 at 15:09
  • Please provide the exact compilation error in your questions (this is probably why all the down votes happened) Commented Jun 7, 2017 at 6: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<something> would work while int wouldn't. The opposite also exists, where P : struct, which requires it to be a value type. Commented Dec 9, 2022 at 9:41

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, you saved me ! Removing the "class" word made it work :-)
My dude, it was surprising how hard it was to find this info. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.