Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

245
Visualizações
What is the difference between init block and constructor in kotlin?

I have started learning Kotlin. I would like to know the difference between init block and constructor. What is the difference between this and how we can use this to improve?

class Person constructor(var name: String, var age: Int) {
    var profession: String = "test"

    init {
        println("Test")
     }    
}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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) {
    constructor(t: String, u: String) : this(t) {
        this.s += u
    }
    init {
        s += "B"
    }
}

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, and then immediately init block starts to execute it will add "B" to the variable. After init block secondary constructor block starts to execute and s will become "TBU".

over 4 years ago · Santiago Trujillo Relatório

0

Since,

The primary constructor cannot contain any code.

https://kotlinlang.org/docs/reference/classes.html

init blocks allow adding code to the primary constructor.

over 4 years ago · Santiago Trujillo Relatório

0

A class in Kotlin class a primary constructor (the one after a class name) which does not contain code, it is only able to initialize properties (e.g. class X(var prop: String)).

The init{..} block in the place, where you can put more code that will run after properties are initialized:

initializer blocks are executed in the same order as they appear in the class body, interleaved with the property initializers

More about that is in https://kotlinlang.org/docs/reference/classes.html#constructors

Here is an example:



class X(var b: String) {
  val a = print("a")

  init {
    print("b")
  }

  constructor() : this("aaa") {
    print("c")
  }
}


X()

When called it prints abc. Thus the init{..} in invoked after primary constructor but before a secondary one.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda