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....