Created
October 24, 2016 23:58
-
-
Save caiorss/ffaf0426fca394cb7bb5456737f359aa to your computer and use it in GitHub Desktop.
Get properties and methods in Scala
This file contains hidden or 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
| // Based on: https://gist.github.com/dajobe/7586938 | |
| // | |
| // | |
| // | |
| // Show object methods | |
| // | |
| def showMethods(x: Any) = | |
| x.getClass.getMethods.map(_.getName).distinct.sorted.foreach(println) | |
| scala> showMethods(Some(10)) | |
| apply | |
| canEqual | |
| collect | |
| ... | |
| filter | |
| filterNot | |
| flatMap | |
| flatten | |
| fold | |
| ... | |
| scala> :paste | |
| // Entering paste mode (ctrl-D to finish) | |
| // Second version | |
| // | |
| def showMethods2(x: Any) = | |
| x.getClass | |
| .getMethods | |
| .map(_.getName) | |
| .distinct | |
| .sorted | |
| .foreach(println) | |
| // Exiting paste mode, now interpreting. | |
| showMethods2: (x: Any)Unit | |
| // ==========> REPL test <================ | |
| scala> showMethods2(Some(10)) | |
| apply | |
| canEqual | |
| collect | |
| contains | |
| copy | |
| copy$default$1 | |
| empty | |
| equals | |
| exists | |
| filter | |
| ... | |
| //-----------------------------------------------------------// | |
| // Based on: https://gist.github.com/dajobe/7586938 | |
| import scala.reflect.runtime.{universe => ru} | |
| import ru._ | |
| def getProperties[T: TypeTag]: Iterable[String] = { | |
| val tpe = ru.typeTag[T].tpe | |
| tpe.declarations.collect { | |
| case m: MethodSymbol if m.isCaseAccessor => m.name.toString | |
| } | |
| } | |
| case class User(name: String, age: Int) { | |
| val other: Long = 0 | |
| } | |
| // ==========> REPL test <================ | |
| scala> getProperties[User] | |
| res2: Iterable[String] = List(name, age) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment