Skip to content

Instantly share code, notes, and snippets.

@scottashipp
Created November 18, 2014 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottashipp/57dcf04538d5bb3ed395 to your computer and use it in GitHub Desktop.
Save scottashipp/57dcf04538d5bb3ed395 to your computer and use it in GitHub Desktop.
Example of use of a companion object to provide the equivalent to Java's static methods and fields.
/* 3. */ object Person {
var nextId: Int = 0;
/* 4. */ def create(first: String, last: String): Person = {
nextId += 1
new Person(first, last, nextId-1)
}
}
class Person /* 1. */ private (private val first: String, private val last: String, private val id: Int) {
def /* 2. */ apply(f: String, l: String, id: Int) =
new Person(first, last, id)
def getName(): String = {
s"$first $last"
}
def getId(): Int = {
id
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment