By Alvin Alexander. Last updated: December 17, 2020
As a brief note today, if you want to see how to create a Scala case class that defines multiple alternate constructors, I hope this example is helpful:
package models
import java.util.Date
// PRIMARY CONSTRUCTOR
case class Url (
id: Long,
longUrl: String,
shortUrl: String,
notes: String,
dateCreated: Date,
numClicks: Long
)
object Url {
// ALTERNATE CONSTRUCTOR #1 (without numClicks)
def apply(
id: Long,
longUrl: String,
shortUrl: String,
notes: String,
dateCreated: Date,
): Url = {
Url(id, longUrl, shortUrl, notes, dateCreated, 0)
}
// ALTERNATE CONSTRUCTOR #2 (without dateCreated or numClicks)
def apply(
id: Long,
longUrl: String,
shortUrl: String,
notes: String
): Url = {
Url(id, longUrl, shortUrl, notes, new Date(), 0)
}
// this is for something else, but i left it here as an `unapply` example
def unapply(u: Url): Option[(Long, String, String, String)] = {
Option(
u.id,
u.longUrl,
u.shortUrl,
u.notes
)
}
}
With that case class defined as shown, you can create new case class instances in the following ways:
val u = Url(id, longUrl, shortUri, notes, dateCreated, numClicks)
val u = Url(id, longUrl, shortUri, notes, dateCreated)
val u = Url(id, longUrl, shortUri, notes)
If you needed to see an example of a case class in Scala with multiple constructors, I hope that helps.