Skip to content

Instantly share code, notes, and snippets.

@itang
Created April 12, 2021 04:02
Show Gist options
  • Save itang/9b57bd721f39398965ba47b067654e10 to your computer and use it in GitHub Desktop.
Save itang/9b57bd721f39398965ba47b067654e10 to your computer and use it in GitHub Desktop.
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