Scala domain object modeling - scala

I'm creating a new domain object mode. In this model, there are Users and Posts. In the future there will be more models (e.g. Comments). I'm trying to learn how to do this using scala to it's full extent. Here's a naive implementation:
class User(val id: String, val creationDate: DateTime, val name: String, val email: String)
class Post(val id: String, val creationDate: DateTime, val user: User, val title: String, val body: String)
And here's another approach attempting to get rid of the duplicate id and creationDate.
class Model(val id: String, val creationDate: DateTime)
class User(id: String, creationDate: DateTime, val name: String, val email: String) extends Model(id, creationDate)
class Post(id: String, creationDate: DateTime, val user: User, val title: String, val body: String) extends Model(id, creationDate)
I'd like to moderate some of my domain objects. To do this, I'd like to add an isApproved: Boolean field.
class Model(val id: String, val creationDate: DateTime)
class User(id: String, creationDate: DateTime, val name: String, val email: String) extends Model(id, creationDate)
class Post(id: String, creationDate: DateTime, val user: User, val title: String, val body: String) extends Model(id, creationDate)
trait Moderated {
val isApproved: Boolean
}
class ModeratedPost(id: String, creationDate: DateTime, val user: User, val title: String, val body: String, val isApproved: Boolean) extends Post(id, creationDate, user, title, body) with Moderated
I'd also like to prevent bugs in my code by type aliasing user and post Ids.
type Id = String
type UserId = Id
type PostId = Id
class Model(val id: Id, val creationDate: DateTime)
class User(id: UserId, creationDate: DateTime, val name: String, val email: String) extends Model(id, creationDate)
class Post(id: PostId, creationDate: DateTime, val user: User, val title: String, val body: String) extends Model(id, creationDate)
trait Moderated {
val isApproved: Boolean
}
class ModeratedPost(id: String, creationDate: DateTime, val user: User, val title: String, val body: String, val isApproved: Boolean) extends Post(id, creationDate, user, title, body) with Moderated
At this point, I've got several questions.
Where should I define my type aliases? I think they have to be defined inside a class, trait, or object.
My goal in using type aliases for my Ids is to catch errors at compile time. I'd like UserId and PostId to be "subclasses" of Id. I.e. if a method took an Id, I could pass in a PostId. How should I do this?
My Moderated trait does not feel very useful. I still have to declare the isApproved on all classes that mix it in. Any tips here?

Idiomatic scala would go something like:
sealed trait Id { def strVal: String }
case class UserId(strVal: String) extends Id
case class PostId(strVal: String) extends Id
trait Model { def id: Id, def creationDate: DateTime)
case class User(
id: UserId,
creationDate: DateTime,
name: String,
email: String
) extends Model
trait Post extends model {
def id: PostId
def user: User,
def title: String,
def body: String
)
trait Moderated { def isApproved: Boolean }
case class UnmoderatedPost(
id: PostId
creationDate: DateTime,
user: User,
title: String,
body: String,
) extends Post
case class ModeratedPost(
id: PostId,
creationDate: DateTime,
user: User,
title: String,
body: String,
isApproved: Boolean
) extends Post with Moderated

You can define your type aliases in package.scala which can be created for each package.
Lets say you have a simple package org.your.project.
Create a file in directory org/your/project called: package.scala
package org.your.project
package object Types {
type Id = String
type UserId = Id
type PostId = Id
}
Then in the class you wish to use the type aliases add:
import org.your.project.Types._
https://stackoverflow.com/a/3401031/2116622
http://www.artima.com/scalazine/articles/package_objects.html
I'd probably not use types for the reasons you are thinking of.
A type of Id could also be an Int but you made it a String.
Anyone reading the code would have to click around the code base to figure out what the Id really is.

Related

Scala Slick and nested case classes

I'm quite new to Scala and need to use slick to build a table mapping for these case classes.
I can do it for a simple case class but the nesting and option parameters are leaving me confused how to do this?
case class Info(fullName: Option[String], dn: Option[String], manager: Option[String], title: Option[String], group: Option[String], sid: Option[String])
case class User(username: String, RiskScore: Float, averageRiskScore: Float, lastSessionId: String, lastActivityTime: Long, info: Info)
I need to end up with a simple table which contains all of the combined parameters.
Given your nested case class definitions, a bidirectional mapping for the * projection similar to the following should work:
case class Info(fullName: Option[String], dn: Option[String], manager: Option[String], title: Option[String], group: Option[String], sid: Option[String])
case class User(username: String, riskScore: Float, averageRiskScore: Float, lastSessionId: String, lastActivityTime: Long, info: Info)
class Users(tag: Tag) extends Table[User](tag, "USERS") {
def username = column[String]("user_name")
def riskScore = column[Float]("risk_score")
def averageRiskScore = column[Float]("average_risk_score")
def lastSessionId = column[String]("last_session_id")
def lastActivityTime = column[Long]("last_acitivity_time")
def fullName = column[Option[String]]("full_name", O.Default(None))
def dn = column[Option[String]]("dn", O.Default(None))
def manager = column[Option[String]]("manager", O.Default(None))
def title = column[Option[String]]("title", O.Default(None))
def group = column[Option[String]]("group", O.Default(None))
def sid = column[Option[String]]("sid", O.Default(None))
def * = (
username, riskScore, averageRiskScore, lastSessionId, lastActivityTime, (
fullName, dn, manager, title, group, sid
)
).shaped <> (
{ case (username, riskScore, averageRiskScore, lastSessionId, lastActivityTime, info) =>
User(username, riskScore, averageRiskScore, lastSessionId, lastActivityTime, Info.tupled.apply(info))
},
{ u: User =>
def f(i: Info) = Info.unapply(i).get
Some((u.username, u.riskScore, u.averageRiskScore, u.lastSessionId, u.lastActivityTime, f(u.info)))
}
)
}
Here is a great relevant Slick article you might find useful.

Scala. Case class copy from trait reference

Hi I'm trying to solve a problem in kind of "elegant" and type safe way but I can't find the best...
Let's say I have this trait
trait Event {
def deviceId: String
def userId: String
def eventDateTime: DateTime
def payload: Option[Payload]
}
trait Payload
And following case classes (there could be more)
case class AEvent (deviceId: String, userId: String, eventDateTime: DateTime, payload: Option[APayload]) extends Event
case class APayload (content: String)
case class BEvent (deviceId: String, userId: String, eventDateTime: DateTime, payload: Option[BPayload]) extends Event
case class BPayload (size: Int, name: String)
I would like to use case class copy method directly from the trait without casting to AEvent or BEvent...
As I'm having a reference to the trait, best solution I figured out is to create a method like this:
def copy[T <: Event](event: T)(deviceId: String = event.deviceId,
userId: String = event.userId,
eventDateTime: DateTime = event.eventDateTime,
payload: Option[Payload] = event.payload) T = {
val res = event match {
case x: AEvent => AEvent(deviceId, userId, eventDateTime, payload.asInstanceOf[APayload])
case x: BEvent => BEvent(deviceId, userId, eventDateTime, payload.asInstanceOf[BPayload])
}
res.asInstanceOf[T]
}
What I don't like is that Payload type is casted in runtime...
How can I have type check during compile time?
Thanks in advance
What about
case class Event[P <: Payload](deviceId: String, userId: String, eventDateTime: DateTime, payload: Option[P])
and using Event[APayload] instead of AEvent?

How to provide ambiguous reference in scala inherit trait?

I have trait, this trait is already defined in framework and can not change:
trait GenericProfile {
def firstName: Option[String]
def lastName: Option[String]
def fullName: Option[String]
def email: Option[String]
def avatarUrl: Option[String]
}
I want a class inherit it as:
class BasicProfile(
providerId: String,
userId: String,
firstName: Option[String],
lastName: Option[String],
fullName: Option[String],
email: Option[String],
avatarUrl: Option[String]
) extends GenericProfile{
def providerId=this.providerId //ambiguous reference will be here
...
}
But if I do not re-define the unimplemented method, there is still error since the value in BasicProfile is regarded as private and do not regard it as already implemented.
I understand that it can simply write as override, but I have another class in practice:
case class IdProfile(id:String,
providerId: String,
userId: String,
firstName: Option[String],
lastName: Option[String],
fullName: Option[String],
email: Option[String],
avatarUrl: Option[String])extends BasicProfile(providerId,userId,firstName,lastName, fullName,email, avatarUrl){
}
I do not want the IdProfile override the methods from its parents class BasicProfile, just inherit would be OK.
Since BasicProfile has to make sure all that the defined methods of the trait are implemented (since you don't want to use an abstract class), I'd recommend using a case class for the BasicProfile.
You can extend the BasicProfile with an IdProfile class (not case class) and override the specific methods you are interesed in (or leave them be). If I'm not mistaken that's what your trying to accomplish?
trait GenericProfile {
def firstName: Option[String]
def lastName: Option[String]
def fullName: Option[String]
def email: Option[String]
def avatarUrl: Option[String]
}
case class BasicProfile(
providerId: String,
userId: String,
var firstName: Option[String],
var lastName: Option[String],
var fullName: Option[String],
var email: Option[String],
var avatarUrl: Option[String]
) extends GenericProfile{
}
class IdProfile(id:String,
providerId: String,
userId: String,
firstName: Option[String],
lastName: Option[String],
fullName: Option[String],
email: Option[String],
avatarUrl: Option[String])extends BasicProfile(providerId,userId,firstName,lastName, fullName,email, avatarUrl){
}
If you are trying to stay away from case class I'd recommend taking a look at this Question: Simple Scala getter/setter override
Hope this helps.
To define a readable field in the argument list to a class's constructor, you can use val:
class BasicProfile(
val providerId: String,
val firstName: Option[String],
...
) extends GenericProfile {
...
}
When you do not put val (or alternatively var for a mutable field) on the constructor argument, a field is generally not created.
If you define your class as a case class, then constructor arguments without modifiers are treated as if they have val in front of them, and fields are created for them:
case class BasicProfile(
providerId: String,
...
) extends GenericProfile {
...
}

scala case class with casbah. Accept objectid parameter as string or as a objectid

I am kind of new to scala and have not done any programming in java or object oriented programming languages.
I have been using this case class to write to the database
case class User(id: new ObjectId, name: String)
What is the best way to let this accept either an ObjectId String, or an ObjectId? Ideally I would like to just have the case class implicitly convert a string to an ObjectId.
You should go for a companion object and a case class eg:
object User {
def apply(name: String): User = User(new ObjectId(), name)
def apply(id: String, name: String): User = User(new ObjectId(id), name)
}
case class User(id: ObjectId, name: String)
Then you can handle either these cases:
val user = User("Ross")
val user1 = User("5204b74d9932e8319b8e9ec0", "Ross")
val user2 = User(new ObjectId(), "Whitehead")

Must override val variable in scala

I meet a weird problem in scala. Following is my code, class Employee extends class Person
But this piece of code can not been compiled, I have explicit define firstName and lastName as val variable. Why is that ? Does it mean I have to override val variable in base class ? And what is the purpose ?
class Person( firstName: String, lastName: String) {
}
class Employee(override val firstName: String, override val lastName: String, val depart: String)
extends Person(firstName,lastName){
}
The input parameters for the constructor are not vals unless you say they are. And if they are already, why override them?
class Person(val firstName: String, val lastName: String) {}
class Strange(
override val firstName: String, override val lastName: String
) extends Person("John","Doe") {}
class Employee(fn: String, ln: String, val depart: String) extends Person(fn,ln) {}
If they're not vals and you want to make vals, you don't need to override:
class Person(firstName: String, lastName: String) {}
class Employee(
val firstName: String, val lastName: String, val depart: String
) extends Person(firstName,lastName) {}
Since the constructor arguments have no val/var declaration in Person, and as Person is no case class, the arguments will not be members of class Person, merely constructor arguments. The compiler is telling you essentially: hey, you said, that firstName and lastName are members, which override/redefine something inherited from a base class - but there is nothing as far as I can tell...
class Person(val firstName: String, val lastName: String)
class Employee(fn: String, ln: String, val salary: BigDecimal) extends Person(fn, ln)
You do not need to declare firstName/lastName as overrides here, btw. Simply forwarding the values to the base class' constructor will do the trick.
You might also consider redesigning your super classes as traits as much as possible. Example:
trait Person {
def firstName: String
def lastName: String
}
class Employee(
val firstName: String,
val lastName: String,
val department: String
) extends Person
or even
trait Employee extends Person {
def department: String
}
class SimpleEmployee(
val firstName: String,
val lastName: String,
val department: String
) extends Employee
Unless I've misunderstood your intention, here's how to extend Person.
Welcome to Scala version 2.8.0.final (Java HotSpot(TM) Client VM, Java 1.6.0_21).
Type in expressions to have them evaluated.
Type :help for more information.
scala> class Person( firstName: String, lastName: String)
defined class Person
scala> class Employee(firstName: String, lastName: String, depart: String) extends Person(firstName, lastName)
defined class Employee