Posts

Showing posts with the label generics

A generic class which can take only certain types

A generic class which can take only certain types Suppose, I want to create a generic class that can take only int and double as types. int double public class A<T> where T: int, double { public T property{get;set;} } For instance: A<int> i = new A<int>(); i.property = 10; A<double> d = new A<double>(); d.property = 0.01; but, this is not working. How can I do that? Is there any other way I can address my specific requirement? You can't - how would you do anything with property within A ? – Lee Jun 27 at 18:32 property A 6 Answers 6 There's no such constraint exists in C#. But for value type you can use struct as generic constraint. It will only allow non-nullable value types. struct public class A<T> w...

Scala - Perform Operation on two objects only if an inner field is equal

Scala - Perform Operation on two objects only if an inner field is equal If I have Class Box[+T] { num: Int, t: T } And I want to make a method which adds two boxes together, but really it just adds num and creates a new Box, how would I do that but ensuring both t's are equal? I don't want just the type to be the same, but the inner part of t to be the same 1 Answer 1 you can do the following: def add[T](box1: Box[T], box2: Box[T]): Option[Box[T]] = { if(box1.t == box2.t) Some(Box(box1.num + box2.num, box1.t)) else None } does this work in the context of this stackoverflow.com/questions/12700693/compare-types-in-scala – Joel Berkeley Jul 1 at 18:43 @JoelBerkeley I think it should. Also, this is OK I suppose....