Why is the Manifest not available in the constructor?

前端 未结 1 1043
南笙
南笙 2021-01-18 04:06

Consider this code:

class Foo[T : Manifest](val id: String = manifest[T].erasure.getName)

I basically want to store an identifier in Foo, w

1条回答
  •  醉梦人生
    2021-01-18 04:26

    When the syntactic sugar is removed from that context bound, it gets rewritten as:

    class Foo[T]
      (val id: String = implicitly[Manifest[T]].erasure.getName)
      (implicit ev$1: Manifest[T]) = ...
    

    So the Manifest evidence simply isn't available when determining the default value of id. I'd instead write something like this:

    class Foo[T : Manifest](id0: String = "") {
      val id = if (id0 != "") id0 else manifest[T].erasure.getName
    }
    

    In your second approach (which is a great solution, by the way!), expect a rewrite similar to:

    class Foo[T](val name: String)(implicit x$1: Manifest[T]) { 
      def this()(implicit ev$2: Manifest[T]) = this(manifest[T].erasure.getName)
    }
    

    So yes, the manifest is available before the call to manifest[T].erasure

    0 讨论(0)
提交回复
热议问题