Created
June 23, 2014 18:07
-
-
Save jenglert/9d99706d0d1d4ba79a5f to your computer and use it in GitHub Desktop.
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
import java.util.Date | |
/** | |
* Usage: | |
* | |
* val someFun: String = SimpleCache({ () => somethingExpensive }, 15.minutes).cachedFun | |
* | |
* val theValue = someFun() | |
*/ | |
class SimpleCache[T]( | |
fun: () => T, | |
cacheTimeInMs: Long | |
) { | |
private var lastUpdated: Date = new Date(0l) | |
private var entry: Option[T] = None | |
def cachedFun: () => T = { | |
if (entry.isDefined && | |
(System.currentTimeMillis() - lastUpdated.getTime() < cacheTimeInMs)) { | |
entry.get _ | |
} else { | |
val result = fun() | |
lastUpdated = new Date | |
entry = Some(result) | |
entry.get _ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment