Skip to content

Instantly share code, notes, and snippets.

@chorandrey
Last active September 5, 2020 17:56
Show Gist options
  • Save chorandrey/36378cc32c1df916fcc8551844b1f253 to your computer and use it in GitHub Desktop.
Save chorandrey/36378cc32c1df916fcc8551844b1f253 to your computer and use it in GitHub Desktop.
Scala this.type example and how to introduce some type level security against supplied values
trait Person {
type PersonType = this.type
}
trait CreditRecord {
type Holder <: Person
val amount: Int
def reduce(h: Holder, reduceAmount: Int) = {
val intermediateAmount = amount - reduceAmount
new CreditRecord {
override type Holder = h.PersonType
override val amount: Int = intermediateAmount
}
}
def print = println(s"CreditRecord(amount=$amount)")
}
object Bank {
def issueCredit[T <: Person](p: Person, _amount: Int) = {
new CreditRecord {
type Holder = p.PersonType
override val amount: Int = _amount
}
}
}
val person1 = new Person {}
val person2 = new Person {}
val credit1 = Bank.issueCredit(person1, 500)
val credit2 = Bank.issueCredit(person2, 200)
val reduced1 = credit1.reduce(person1, 100)
reduced1.print
val reduced2 = reduced1.reduce(person1, 10)
reduced2.print
//val mistaken = credit1.reduce(person2, 20) // pay attention to "person2" in parameters. This code would not compile
//mistaken.print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment