Created
April 4, 2012 11:14
-
-
Save halfninja/2300423 to your computer and use it in GitHub Desktop.
Useful Scala snippets
This file contains hidden or 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
| def newTempFile() = new File(IoTmpDir, "JavaTestTmp-"+random.nextLong()) | |
| /* | |
| * Tries 10 times to find a nonexistent file. | |
| * Uses Streams to lazily go through a range, generating a fresh | |
| * file each time. | |
| */ | |
| val dir = Stream.range(1,10) | |
| .map { newTempFile() } | |
| .find(!_.exists) | |
| .getOrElse(throw new IllegalStateException("Couldn't find unique filename!")) | |
| /* | |
| * This form might be better, because it's using Iterator (which doesn't bother caching elements) | |
| * and directly creates a file generator rather than mapping onto a stream of numbers that aren't used. | |
| * The take() call doesn't evaluate anything in an Iterator, it just limits it to returning max 10 items. | |
| */ | |
| val dir = Iterator.continually { newTempFile() }.take(10) | |
| .find(!_.exists) | |
| .getOrElse(throw new IllegalStateException("Couldn't find unique filename!")) | |
| /* | |
| * If you do not fear infinity's grasp, you could retry indefinitely. | |
| * If you expected to go through a large number of items, discarding all but one, | |
| * it may be better to use Iterator which doesn't keep previous items in memory. | |
| */ | |
| val dir = Stream.continually( newTempFile() ) | |
| .find(!_.exists).get // It'll either return Some, or NEVER return. Careful! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment