Is There Difference Between Using a Constructor and Using .Init

Is there difference between using a constructor and using .init?

From the Initializer Expression section of the language guide:

If you specify a type by name, you can access the type’s initializer without using an initializer expression. In all other cases, you must use an initializer expression.

let s1 = SomeType.init(data: 3) // Valid

let s2 = SomeType(data: 1) // Also valid

let s3 = type(of: someValue).init(data: 7) // Valid

let s4 = type(of: someValue)(data: 5) // Error

Initializing using the explicit .init on the type directly is no different than without it; they are equivalent from Swift's perspective, so most folks prefer the brevity of omitting .init.

What is the difference between init block and constructor in kotlin?

The init block will execute immediately after the primary constructor. Initializer blocks effectively become part of the primary constructor.

The constructor is the secondary constructor. Delegation to the primary constructor happens as the first statement of a secondary constructor, so the code in all initializer blocks is executed before the secondary constructor body.

Example

class Sample(private var s : String) {
init {
s += "B"
}
constructor(t: String, u: String) : this(t) {
this.s += u
}
}

Think you initialized the Sample class with

Sample("T","U")

You will get a string response at variable s as "TBU".

Value "T" is assigned to s from the primary constructor of Sample class.

Then immediately the init block starts to execute; it will add "B" to the s variable.

Next it is the secondary constructor turn; now "U" is added to the s variable to become "TBU".

__init__ as a constructor?

If you have a class Foo then:

  • Foo() is the constructor
  • Foo.__init__() is the initializer
  • Foo.__new__() is the allocator

Construction of a Python object is simply allocation of a new instance followed by initialization of said instance.

Difference between using class() and class.init() in swift

Both are allowed and are equivalent. As The Swift Programming Language says:

If you specify a type by name, you can access the type’s initializer without using an initializer expression. In all other cases, you must use an initializer expression.

let s1 = SomeType.init(data: 3)  // Valid
let s2 = SomeType(data: 1) // Also valid

let s3 = type(of: someValue).init(data: 7) // Valid
let s4 = type(of: someValue)(data: 5) // Error

So, when you’re supplying the name of the type when instantiating it, you can either use the SomeType(data: 3) syntax or SomeType.init(data: 3). Most Swift developers would favor SomeType(data: 3) as we generally favor brevity unless the more verbose syntax lends greater clarity, which it doesn’t in this case. That having been said, SomeType.init(data: 3) is permitted, though it is less common in practice.

What is difference between create object with init and () in Swift

There is no functional difference between the two. Both styles will call the same initializer and produce the same value.


Most style guides that I've seen prefer to leave out the explicit .init-part in favor of the shorter A(value:) syntax — that also resembles the constructor syntax in many other languages.

That said, there are some scenarios where it's useful to be able to explicitly reference the initializer. For example:

  • when the type can be inferred and the act of initialization is more important than the type being initialized. Being able to call return .init(/* ... */) rather than return SomeComplicatedType(/* ... */) or let array: [SomeComplicatedType] = [.init(/* ... */), .init(/* ... */)]

  • when passing the initializer to a higher order function, being able to pass "something".map(String.init) rather than "something".map({ String($0) })

Again, it's a matter of style.

What is the difference between initState and a class constructor in Flutter?

The difference is (in the context of creating a State object) which has the initState() method:

  • constructor simply create a new State instance

  • initState() is called after the object is created and at this point
    you have access to the BuildContext or the StatefulWidget to which the State is attached to, respectively using the context and the widget properties. At this point the State is already mounted.

Reference State: https://api.flutter.dev/flutter/widgets/State-class.html

Reference mounted State: https://api.flutter.dev/flutter/widgets/State/mounted.html

What's the difference between __construct() and init()

init() is called by the constructor.

init() isn't defined in the specification of PHP, it's only a method available with the Zend Framework to help initialize without having to rewrite the constructor yourself.


On the same topic :

  • Zend Framework: What are the differences between init() and preDispatch() functions in controller objects?

Why use an initialization method instead of a constructor?

Since they say "timing", I guess it's because they want their init functions to be able to call virtual functions on the object. This doesn't always work in a constructor, because in the constructor of the base class, the derived class part of the object "doesn't exist yet", and in particular you can't access virtual functions defined in the derived class. Instead, the base class version of the function is called, if defined. If it's not defined, (implying that the function is pure virtual), you get undefined behavior.

The other common reason for init functions is a desire to avoid exceptions, but that's a pretty old-school programming style (and whether it's a good idea is a whole argument of its own). It has nothing to do with things that can't work in a constructor, rather to do with the fact that constructors can't return an error value if something fails. So to the extent that your colleagues have given you the real reasons, I suspect this isn't it.

Why do we need __init__ to initialize a python class

Citation: But I can also do

class myClass():
x = 3
print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)

No you cannot. There is a fundamental difference once you want to create two or more objects of the same class. Maybe this behaviour becomes clearer like this

class MyClass:
x = 3
print("Created!")

a = MyClass() # Will output "Created!"
a = MyClass() # Will output nothing since the class already exists!

In principle you need __init__ in order to write that code that needs to get executed for every new object whenever this object gets initialized / created - not just once when the class is read in.



Related Topics



Leave a reply



Submit