简体   繁体   中英

Define custom HashSet in Scala?

Basically I have three variables a,b and c. The variables have certain relationship among them. I need to store the variables in a HashSet so that each variable will be different and there wont be any redundancy.

Java way:

In java I just create a custom class, override hash and equal methods in that custom class and I will be done.

HashSet<CustomClass> hSet = new HashSet<CustomClass>();

Scala way (Scala newbie):

Introduction to Sets and Maps for Scala

Here I am confused to choose between a trait , class and an object. Obviously at the first look I cannot have trait and class assigned to a var / val (Please let me know if the above can be done). So object is the way to go.

object State {
    var a: Int;
    var b: Int;
    var c: Int;
}

Question 1: How should I define a custom (class/trait/object) HashSet?

Normal HashSet declaration in Scala: var hSet = new HashSet();

Question 2: How to assign value to the new object? for example,

var newState = State;
newState.a = 100;
hSet.add(newState);

Error : type mismatch; found : Int(100) required: Int.type

Thank you

The short answer is: the Scala way is the same as the Java way. That said, case classes can help you by automatically constructing a valid hash and equals methods (and toString and apply for that matter). It goes like this:

case class MyClass(myInt: Int, myString: String)
val hSet = new mutable.HashSet[MyClass]();
hSet += MyCLass(2, "foo") 

Note that HashSets have type parameters, just as in Java. For immutable sets the syntax varies a little, but comming from Java this will feel easier.

Also, when you define an object you are basically defining a class with a single instance (a singleton pattern). This is clearly not what you want here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM