Is it possible for Scala to have reified generics without changing the JVM?

后端 未结 5 1919
谎友^
谎友^ 2021-01-03 19:29

I\'ve recently started learning Scala and was disappointed (but not surprised) that their generics are also implemented via type erasure.

My question is, is it possi

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-03 19:32

    "implicit Manifest" is a Scala compiler trick and it does not make generics in Scala reified. The Scala compiler, when it sees a function with "implicit m: Manifest[A]" parameter and it knows the generic type of A at the call site, it will wrap the class of A and its generic type parameters into a Manifest and make it available inside the function. However, if it could not figure out the true type of A, then it has no way of creating a Manifest. In other words, Manifest has to be passed along the function calling chain if the inner function needs it.

    scala> def typeName[A](a: A)(implicit m: reflect.Manifest[A]) = m.toString
    typeName: [A](a: A)(implicit m: scala.reflect.Manifest[A])java.lang.String
    
    scala> typeName(List(1))
    res6: java.lang.String = scala.collection.immutable.List[int]
    
    scala> def foo[A](a: A) = typeName(a)
    :5: error: could not find implicit value for parameter m:scala.reflect.Manifest[A].
           def foo[A](a: A) = typeName(a)
                                      ^
    
    scala> def foo[A](a: A)(implicit m: reflect.Manifest[A]) = typeName(a)
    foo: [A](a: A)(implicit m: scala.reflect.Manifest[A])java.lang.String
    
    scala> foo(Set("hello"))
    res8: java.lang.String = scala.collection.immutable.Set[java.lang.String]
    

提交回复
热议问题