Created
January 30, 2014 02:24
-
-
Save mather/8701484 to your computer and use it in GitHub Desktop.
Scalaの列挙型をJavaから参照してみる ref: http://qiita.com/mather314/items/9c0e58578597e264c41d
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
public class Main { | |
public static void main(String[] args) { | |
// Signal class | |
System.out.println(Signal.class.toString()); | |
// Signal$ class (Signal.type @ Scala) | |
System.out.println(Signal$.class.toString()); | |
// Signal singleton object | |
Signal$ obj = Signal$.MODULE$; | |
System.out.println(obj.toString()); | |
// Get enumeration instance | |
System.out.println(Signal.Green().toString()); | |
System.out.println(Signal.apply(2).toString()); | |
System.out.println(Signal.withName("RED").toString()); | |
System.out.println(Signal.valueOf("RED").toString()); | |
// Instance Type (Inner class of singleton object class) | |
Signal$.Value a = Signal.Yellow(); | |
System.out.println(a.id()); | |
// Use methods explicitly | |
System.out.println(new Signal.JavaLikeValue(Signal.Green()).name()); | |
} | |
} |
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
/** | |
* Use Signal | |
*/ | |
object ScalaMain extends App { | |
// Iteration | |
Signal.values.foreach { signal => | |
println(s"id: ${signal.id}, toString: ${signal}") | |
} | |
// Get singleton instance | |
val g = Signal.Green | |
val y = Signal(2) // by id | |
val r = Signal.withName("RED") // by name | |
// Mapping function | |
def toMessage = { | |
import Signal._ // import for shortcut | |
// pattern match (like switch-case in Java) | |
(_: Value) match { | |
case Green => "Go ahead" | |
case Yellow => "Be careful" | |
case Red => "Stop" | |
} | |
} | |
println( toMessage(r) ) | |
// implicit conversion | |
println( g.name ) | |
println( y.ordinal ) | |
} |
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
/** | |
* Define Signal Enumeration | |
*/ | |
object Signal extends Enumeration { | |
val Green = Value //=> Val(0, "Green") | |
val Yellow = Value(2) //=> Val(2, "Yellow") | |
val Red = Value("RED") //=> Val(3, "RED") | |
// Alias for Java | |
def valueOf(name: String) = withName(name) | |
// Java-like methods addition (can't use implicitly from Java) | |
implicit class JavaLikeValue(v: Value) { | |
def name = v.toString | |
def ordinal = v.id | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment