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

Multi tool use
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
}





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

j2M3h4fUhpBRK
jP kZ 6Zpq3W9UKF X59 Oa6cMEk8vgPN5,mqKl

Popular posts from this blog

Rothschild family

Cinema of Italy