Scala では、実行時に型の文字列表現を取得することは可能ですか? 私はこれらの行に沿って何かをしようとしています:
def printTheNameOfThisType[T]() = {
println(T.toString)
}
Scala 2.10TypeTag
以降では、完全な型情報を含む を使用します。scala-reflect
これを行うには、ライブラリを含める必要があります。
import scala.reflect.runtime.universe._
def printTheNameOfThisType[T: TypeTag]() = {
println(typeOf[T].toString)
}
次のような結果が得られます。
scala> printTheNameOfThisType[Int]
Int
scala> printTheNameOfThisType[String]
String
scala> printTheNameOfThisType[List[Int]]
scala.List[Int]
Scala 2.10以降のTypeTagを使用して回答を参照してください
freenode で #Scala を勧めてもいいですか
10:48 <seet_> http://stackoverflow.com/questions/190368/getting-the-string-representation-of-a-type-at-runtime-in-scala <-- isnt this posible?
10:48 <seet_> possible
10:48 <lambdabot> Title: Getting the string representation of a type at runtime in Scala - Stack Overflow,
http://tinyurl.com/53242l
10:49 <mapreduce> Types aren't objects.
10:49 <mapreduce> or values
10:49 <mapreduce> println(classOf[T]) should give you something, but probably not what you want.
Scala には「マニフェスト」と呼ばれる、ほとんど文書化されていない新しい機能があります。それはこのように動作します:
object Foo {
def apply[T <: AnyRef](t: T)(implicit m: scala.reflect.Manifest[T]) = println("t was " + t.toString + " of class " + t.getClass.getName() + ", erased from " + m.erasure)
}
AnyRef バウンドは、値に .toString メソッドがあることを確認するためのものです。
これは実際には「事」ではないことに注意してください。
object Test {
def main (args : Array[String]) {
println(classOf[List[String]])
}
}
与える
$ scala Test
class scala.List
私はあなたがこれを消去のせいにすることができると思います
====編集====ジェネリック型パラメーターを持つメソッドでそれを試してみました:
object TestSv {
def main(args:Array[String]){
narf[String]
}
def narf[T](){
println(classOf[T])
}
}
そして、コンパイラはそれを受け入れません。タイプはクラスではなく説明です