Created
November 18, 2014 00:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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