rbs icon indicating copy to clipboard operation
rbs copied to clipboard

Should return void at `#initialize`

Open ksss opened this issue 1 year ago • 2 comments

There is a problem if the #initialize type is fixed.

The user must match or override the return type of #initialize in the inherited class. The #initialize does not need to care about the return type, and it should be possible that it may change in the future.

This PR has been modified to unify all #initialize method return types with void.

ksss avatar Mar 11 '24 01:03 ksss

I'm not a huge fan of this, as I can see situations where people might want to do custom overrides of initialize. But I dont have a big enough reason other than "this seems unnecessarily restrictive" to reject it

sw-square avatar Mar 14 '24 18:03 sw-square

@sw-square Thank you for reviewing.

An example I can think of is as follows.

# sample/cli.rb
module Sample
  class CLI
    class << self
      attr_accessor :logger
    end

    # Cannot allow method body have type `::Logger` because declared as type `nil`
    #   ::Logger <: nil(Ruby::MethodBodyTypeMismatch)
    def initialize
      CLI.logger = Logger.new($stdout)
    end
  end
end

When I used steep, Sample::CLI#initialize gave me a type error.

There are two ways to resolve this type error. Either put nil at the end of #initialize or write the type of Sample::CLI#initialize.

# sample/cli.rb
module Sample
  class CLI
    def initialize
      CLI.logger = Logger.new($stdout)
      nil
    end
  end
end

or

# sample/cli.rbs
module Sample
  class CLI
    def initialize: () -> void
  end
end

Neither of those methods seems like the best way to me.

ksss avatar Mar 15 '24 01:03 ksss