Reputation: 68
New to scala, what is the best way to implement this method. I am trying to get this value output from the method below and assign it to a case class. Bit rusty on the OOP practices.
/** A container for storing car table fields */
case class car(
UUID??
color:String,
model:String,
type:String,
)
Basicaly my question what is the best way to create an instance of the below rand value to the case class car above. Create another class and call it or implement with in the same scala class?
def rand = new Random()
def randomClockSeqAndNodeFields = {
var lsb: Long = 0
lsb |= 0x8000000000000000L // variant (2 bits)
lsb |= ( rand.synchronized { rand.nextLong } & 0x3FFFFFFFFFFFFFFFL)
lsb
}
Upvotes: 1
Views: 1323
Reputation: 19527
One way to organize this code is to define a companion object:
object Car {
def rand = new Random()
def randomClockSeqAndNodeFields = { ... }
}
case class Car(
UUID: Long = Car.randomClockSeqAndNodeFields,
color: String,
model: String,
make: String
)
You can call your method inside the declaration of your case class, and that method will, by default, be called for every instance of the class. Note that I capitalized the class name to follow standard naming conventions, and I renamed type
to make
because type
is a keyword.
To create a Car
instance:
val myCar = Car(color="black", model="wrangler", make="jeep")
The creation of every Car
instance, if you don't explicitly pass in a value for the UUID
parameter, will call randomClockSeqAndNodeFields
, generating a new UUID for that car. Alternatively, you could define Car
as...
case class Car(
UUID: Long,
color: String,
model: String,
make: String
)
...in which case you'd have to explicitly call randomClockSeqAndNodeFields
every time you create an instance:
val myCar = Car(Car.randomClockSeqAndNodeFields, "black", "wrangler", "jeep")
Upvotes: 1
Reputation: 8036
I suggest, since UUID is a java supported type :
/** A container for storing car table fields */
case class car(
uuid: UUID = UUID.randomUUID(),
color:String,
model:String,
type:String,
)
Upvotes: 3