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

Multi tool use
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
}
@JoelBerkeley I think it should. Also, this is OK I suppose. I was hoping to avoid the Option. It seems there would not be a way to get safety at compilation (without having Option return type) even if we restricted it to the same object reference must be in each Box. The thing is it's more of a programmer error that someone would try to add two different boxes, which is why I don't like the Option; it seems more silent. I'm wondering if it would be better to throw an exception or have a require( ) statement used instead
– Jordan Cutler
Jul 1 at 19:19
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
does this work in the context of this stackoverflow.com/questions/12700693/compare-types-in-scala
– Joel Berkeley
Jul 1 at 18:43