-
Notifications
You must be signed in to change notification settings - Fork 58
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add suugested extended enum puzzler (which also applies to any class-…
…level extensions) #23
- Loading branch information
1 parent
a6d5504
commit 1507cdf
Showing
2 changed files
with
34 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
Correct answer: ***d) will not compile*** | ||
|
||
* Extension functions on Color apply to instances of Color, e.g. `Color.Blue.from()` | ||
* Extension function on the enum itself can be made only if it has a Companion object | ||
``` | ||
enum class Color { | ||
Red, Green, Blue; | ||
companion object | ||
} | ||
fun Color.Companion.from(...) | ||
``` | ||
|
||
Puzzler by Dmitry Kandalov @dkandalov |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
package types.extendedEnum | ||
|
||
enum class Color { | ||
Red, Green, Blue | ||
} | ||
|
||
fun Color.from(s: String) = when (s) { | ||
"#FF0000" -> Color.Red | ||
"#00FF00" -> Color.Green | ||
"#0000FF" -> Color.Blue | ||
else -> null | ||
} | ||
|
||
println(Color.from("#00FF00")) | ||
|
||
// What will it print? | ||
// a) Green | ||
// b) Color.Green | ||
// c) null | ||
// d) will not compile |