Skip to content

Instantly share code, notes, and snippets.

@erikerlandson
Last active March 22, 2017 13:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikerlandson/78d8c33419055b98d701 to your computer and use it in GitHub Desktop.
Save erikerlandson/78d8c33419055b98d701 to your computer and use it in GitHub Desktop.
Function that returns a human readable string that describes the type of its argument
scala> import TypeString._
import TypeString._
scala> typeString[Int]
res1: String = Int
scala> typeString(2)
res2: String = Int
scala> typeString[String => Int]
res3: String = (String)=>Int
scala> typeString((x:String)=>x.toInt)
res4: String = (String)=>Int
import scala.reflect.runtime.universe._
object TypeString {
// return a human-readable type string for type argument 'T'
// typeString[Int] returns "Int"
def typeString[T :TypeTag]: String = {
def work(t: Type): String = {
t match { case TypeRef(pre, sym, args) =>
val ss = sym.toString.stripPrefix("trait ").stripPrefix("class ").stripPrefix("type ")
val as = args.map(work)
if (ss.startsWith("Function")) {
val arity = args.length - 1
"(" + (as.take(arity).mkString(",")) + ")" + "=>" + as.drop(arity).head
} else {
if (args.length <= 0) ss else (ss + "[" + as.mkString(",") + "]")
}
}
}
work(typeOf[T])
}
// get the type string of an argument:
// typeString(2) returns "Int"
def typeString[T :TypeTag](x: T): String = typeString[T]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment