admin管理员组

文章数量:1415684

I'm creating a factory/builder class that returns a generic type:

instance = ClientsFactory[SomeClass].new(:name).build

but I also want to have a static method to call it directly:

instance = ClientsFactory[SomeClass].build(:name)

Problem is, the latter doesn't accept the type annotation, giving me the following error:

Call to method build on ClientsFactory[SomeClass] mistakes a type for a value

Is there a way to use Generics with static methods to return a dynamic type?

I'm creating a factory/builder class that returns a generic type:

instance = ClientsFactory[SomeClass].new(:name).build

but I also want to have a static method to call it directly:

instance = ClientsFactory[SomeClass].build(:name)

Problem is, the latter doesn't accept the type annotation, giving me the following error:

Call to method build on ClientsFactory[SomeClass] mistakes a type for a value

Is there a way to use Generics with static methods to return a dynamic type?

Share Improve this question asked Feb 4 at 18:15 paulodiovanipaulodiovani 1,3052 gold badges16 silver badges35 bronze badges 1
  • 1 See also: stackoverflow/q/62281301/3141234 – Alexander Commented Feb 5 at 14:31
Add a comment  | 

1 Answer 1

Reset to default 0

You would need to make your method generic as well:

Sorbet.run

# typed: true

class ClientsFactory
  extend T::Generic
  extend T::Sig

  Result = type_member

  class << self
    extend T::Sig
    sig do
      type_parameters(:T)
        .params(type: T.type_parameter(:T), sym: Symbol)
        .returns(ClientsFactory[T.type_parameter(:T)])
    end
    def build(type, sym)
      new # dummy implementation
    end
  end
end

instance = ClientsFactory.build(String, :name)

本文标签: rubyUsing Sorbet Generics with static methodsStack Overflow