1
def getManifest[T : Manifest] = implicitly[Manifest[T]]

class A[T] 
object A {
    def apply[T] = new A[T]
} 
def getA[T : A] = implicitly[A[T]] 

val m = getManifest[Int] 
//res0: Manifest[Int] = Int

val a = getA[Int]
//<console>:14: error: could not find implicit value for evidence parameter of type A[Int] 

Even though there is no implicit variable in context

by calling getManifest[Int], m of type Manifest[Int] is caputred implicitly


However my custom class A, getA[Int] emits an error

Because there is no implicit variable in cotext.


What is the difference between class A and Manifest

does Scala compiler knows about Manifest and do some magic ???

like, creating some implicit variables for Manifest

Wonpyo Park
  • 301
  • 3
  • 11

1 Answers1

2

Short answer is yes. Manifests are compiler magic where the Scala compiler will automatically conjure up implicit instances of them for types as they are needed. They're used to get around type erasure on the JVM (the problem that at runtime generic types get erased so for example a List[Int] looks the same as a List[String]).

See What is a Manifest in Scala and when do you need it? for more details.

They are also deprecated now in favor of TypeTags.

badcook
  • 3,699
  • 14
  • 25
  • Thanks, your answer is very helpful. is it possible to make my custom class A to act like Manifest ? – Wonpyo Park Oct 30 '16 at 09:56
  • 1
    Some uses should be replaced by `TypeTag`s, other by `ClassTag`s. – Alexey Romanov Oct 30 '16 at 12:19
  • @WonpyoPark, no, although there's a chance implicit conversions will probably get you what you want. In particular, you're going to need to tell the compiler how to get an `A` from any type `T` and one way of doing that is via implicit conversions. – badcook Nov 07 '16 at 00:23
  • @AlexeyRomanov purely out of curiosity, have you run into any cases in the wild where `TypeTag` wouldn't do and you chose `ClassTag` instead? – badcook Nov 07 '16 at 00:56
  • @badcook Probably the most common one is matching `case x: A` (where `A` is a type parameter). It works when you have a `ClassTag[A]` in scope, but not with a `TypeTag[A]`. Also you often need a `ClassTag` to work with arrays. – Alexey Romanov Nov 07 '16 at 06:53