Reified generics in Scala 2.10

前端 未结 3 933
轻奢々
轻奢々 2021-02-01 04:04

The lack of reified generics in Scala is the thing that bugs me the most about the language, since simple things cannot be implemented without using complicated constructs.

3条回答
  •  遇见更好的自我
    2021-02-01 04:15

    Kotlin has reified generics for inline function type parameters, as documented here: https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters. This has existed in Kotlin for some time now, they are used by many libraries already within the Kotlin ecosystem. Other answers here are out of date when referring to the Kotlin. Kotlin has been released as 1.0 since February, 2016.

    Examples of reified generics in Kotlin, the famous TypeReference in Jackson, when used in the Jackson Kotlin module uses this code:

    public inline fun  ObjectMapper.readValue(jp: JsonParser): T 
         = readValue(jp, object: TypeReference() {})
    

    And the same thing from the Kotlin based Injekt library:

    public inline fun  fullType(): FullTypeReference 
        = object:FullTypeReference(){}
    
    public inline fun  injectLazy(): Lazy {
        return lazy { Injekt.get(fullType()) }
    }
    

提交回复
热议问题