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

220
Visualizações
What makes the String class in Kotlin to be able to work with square brackets?

In Kotlin you can do something like this:

val s: String = "Hey"
println(s[1])

or simply:

println("Hey"[1])

and you will print e.

But what if you want to extend this behavior to your own classes? What interface do you need to implement to accomplish this syntax?

I looked at String's supertypes and only found Comparable<String> and CharSequence, neither of which had any other supertypes themselves, so my quest ended early.

For example in Python, by defining a method called __getitem__ in a class, you can bestow the objects of that class the ability to be used with square brackets syntax like this a[i]; I was wondering how this was possible in Kotlin.

Thanks in advance.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can use Kotlin's operator overloading, specifically the overloading for indexed access operators.

The syntax "Hey"[1] is just an alias for "Hey".get(1) (if not on the left-hand side of an assignment, where it would be an alias for "Hey".set(1, ...)).

over 4 years ago · Santiago Trujillo Relatório

0

Apparently just having a method get(i: Int) suffices. Interesting...

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