|
package game |
|
import scala.collection.JavaConverters._ |
|
|
|
case class Game(teams: List[String], winner: Option[String]) { g => |
|
// todo turn this into a macro |
|
final class JythonGame { |
|
def getWinner(): String = g.winner.orNull |
|
def getAsScala(): Game = g |
|
def getTeams(): java.util.List[String] = teams.asJava |
|
def __iter__(): org.python.core.PyObject = new org.python.core.PyIterator { |
|
private val objIterator = winner.map(_ => "winner").toIterator ++ Iterator("teams", "asScala") |
|
override def __iternext__(): org.python.core.PyObject = if ( objIterator.hasNext ) new org.python.core.PyString(objIterator.next) else null |
|
} |
|
} |
|
def this(teams: java.util.List[String], winner: String) = this(teams.asScala.toList, Option(winner)) |
|
def getJython(): JythonGame = new JythonGame() |
|
} |
|
|
|
/** |
|
scalac -cp /usr/local/Cellar/jython/2.7.0/libexec/jython.jar Game.scala |
|
jython -J-cp .:/usr/local/Cellar/scala/2.12.0/libexec/lib/scala-library.jar |
|
|
|
>>> import game |
|
>>> game.Game(["A","B","C"], None) |
|
Game(List(A, B, C),None) |
|
>>> game.Game(["A","B","C"], None).jython |
|
game.Game$JythonGame@55a8dc49 |
|
>>> "winner" in game.Game(["A","B","C"], None).jython |
|
False |
|
>>> "winner" in game.Game(["A","B","C"], "John").jython |
|
True |
|
>>> game.Game(["A","B","C"], "John").jython.winner |
|
u'John' |
|
>>> game.Game(["A","B","C"], "John").jython.teams |
|
[A, B, C] |
|
>>> game.Game(["A","B","C"], "John").jython.asScala |
|
Game(List(A, B, C),Some(John)) |
|
|
|
So from Jython, we can refer to both JSON-loaded (for development) and Scala objects very easily. |
|
**/ |