Created
October 11, 2017 08:34
-
-
Save scravy/dd80017ab62c253280527131b80cea1e 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
package com.simplaex.gist | |
import java.util.Objects | |
object ToString { | |
trait Formattable { | |
override def toString: String = { | |
val sb = new StringBuilder | |
for (field <- getClass.getDeclaredFields if !field.isSynthetic) { | |
val name = field.getName | |
field.setAccessible(true) | |
val value = field.get(this) | |
sb.append(name) | |
sb.append(" = ") | |
value match { | |
case x: Array[_] => | |
sb.append(x.mkString("[", ",", "]")) | |
case x => | |
sb.append(Objects.toString(x)) | |
} | |
sb.append("\n") | |
} | |
sb.toString | |
} | |
} | |
case class X(a: Array[Int], b: String) extends Formattable | |
def main(args: Array[String]): Unit = { | |
println(X(Array[Int](1, 2, 3), "hello")) | |
// prints | |
// a = [1,2,3] | |
// b = hello | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment