Created
May 11, 2016 13:15
-
-
Save bradkarels/e829fd8e80b2da41c4122526d819f6ad to your computer and use it in GitHub Desktop.
When you see a trait being "instantiated", be mindful that what is actually happening is that an anonymous class is being instantiated for you.
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
// Given a simple trait | |
trait NiceTrait { | |
def isNice(s: String): Boolean = s match { | |
case "nice" => true | |
case _ => false | |
} | |
} | |
//It is possible to "instantiate" this trait two ways, manually create a class and instantiate that: | |
class MyClass extends NiceTrait | |
val niceness = new MyClass | |
//This is a shorthand mechanism where an anonymous class is implicitly created: | |
val niceness2 = new NiceTrait{} | |
// Put another way, the above creates an anonymous class that extends the trait and instantiates the anonymous class. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment