Created
April 12, 2021 04:02
-
-
Save itang/9b57bd721f39398965ba47b067654e10 to your computer and use it in GitHub Desktop.
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
import scala.language.{dynamics, unsafeNulls} | |
class DynamicBO(m: Map[String, Any]) extends Selectable, Dynamic { | |
def selectDynamic(name: String): Any = m.getOrElse(name, null) | |
} | |
type User = DynamicBO {val name: String; val age: Int} | |
abstract class BaseDynamic extends Dynamic | |
// https://www.scala-lang.org/api/current/scala/Dynamic.html | |
class DynamicBO2(m: collection.mutable.Map[String, Any]) extends BaseDynamic { | |
def selectDynamic(name: String): Any = m.getOrElse(name, null) | |
def updateDynamic(name: String)(value: Any): Unit = m.update(name, value) | |
def applyDynamic(name: String)(args: Any*): Any = { | |
println(s"name: ${name}, args: ${args}") | |
return () | |
} | |
} | |
@main | |
def main(): Unit = time { | |
val bo = DynamicBO(Map("name" -> "itang", "age" -> 39)).asInstanceOf[User] | |
bo.name |> println | |
bo.age |> println | |
bo.address |> println | |
val bo2 = DynamicBO2(collection.mutable.Map("name" -> "tqibm", "age" -> 25)) | |
bo2.name |> println | |
bo2.age |> println | |
bo2.age = 30 | |
bo2.age |> println | |
bo2.setName("tom") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment