Home  >  Q&A  >  body text

java - scala builder pattern 泛型函数调用

黄舟黄舟2714 days ago457

reply all(1)I'll reply

  • 阿神

    阿神2017-04-18 10:12:09

    I happened to encounter the same problem.
    I don’t know how you can use methods 1 and 2 correctly, the simplest method is also required

    asInstanceOf[ManagedChannelBuilder[_]]
    

    Actually

    public static ManagedChannelBuilder<?> forTarget(String target) {
        return ManagedChannelProvider.provider().builderForTarget(target);
    }
    

    What is returned is ManagedChannelBuilder[Any]. In fact, it shouldn't be Any here. But a

    T extends ManagedChannelBuilder<T>
    

    Then nameResolverFactory returns this T as Any.
    Then it becomes calling the build method of Any, which obviously cannot pass compilation.

    I hope there is a better way~

    ==================================================== ==
    Update

    Simplify the problem:

    class A[T <: A[T]] {
        def retA: A[_] = ???
        
        def retT: T = ???
    }
        
    class B extends A[B]
        
    (new B).retA.retT

    This is the original definition. If you change it to this
    def retA: A[_ <: A[_]] = ???
    it should be fine.

    So, it can be like this

    (new B).retA.asInstanceOf[A[_ <: A[_]]].retT.retT....

    Similarly, when returning ManagedChannelBuilder<?>, ManagedChannelBuilder<?>的时候就
    .asInstanceOf[ManagedChannelBuilder[_ <: ManagedChannelBuilder[_]]].asInstanceOf[ManagedChannelBuilder[_ <: ManagedChannelBuilder[_]]]

    reply
    0
  • Cancelreply