Last active
March 22, 2017 13:23
-
-
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
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
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 |
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.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