Why do we return void for initializers? #2028
-
Hello I was curious why the documentation repeatedly returns |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
When you instantiate a class, you call the class method The initializer we typically override is the instance method
|
Beta Was this translation helpful? Give feedback.
-
One reason is that Another reason concerns issues when defining the For example, before the change in #2008, the definition of # rbs
class BasicObject
def initialize: () -> nil
end Now, suppose you define a class that inherits from # rb
class Foo < BasicObject
def initialize
@foo = :default
end
end This code results in a type error because the return types of
# rb
class Foo < BasicObject
def initialize
@foo = :default
nil
end
end
# rbs
class Foo < BasicObject
def initialize: () -> Symbol
end I don’t find either solution practical. Therefore, I believe the return type of To more actively convey the intent that the return type should not be used, I specify This idea has now been implemented as a Cop in RuboCop and is being actively used. |
Beta Was this translation helpful? Give feedback.
When you instantiate a class, you call the class method
new
(e.g.,User.new
).Class#new
is the one that returnsinstance
.The initializer we typically override is the instance method
initialize
, which is merely a callbackClass#new
triggers.initialize
s seldom explicitly returnself
– think about all thedef initialize
blocks you’ve written.