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

204
Visualizações
Scoping Java static methods in Kotlin

There's have a Java library's class which has aVeryLongNameThatIDontWantToTypeEveryTime. This class has a few static methods with generic names: get(), abs() etc.

Now I need to construct complicated calls with them in my kotlin code like this one:

aVeryLongNameThatIDontWantToTypeEveryTime.get(aVeryLongNameThatIDontWantToTypeEveryTime.abs(aVeryLongNameThatIDontWantToTypeEveryTime.get(...), aVeryLongNameThatIDontWantToTypeEveryTime.get(...)))

Now, I would like to use a local scoping function in order to not repeat myself so often. However, simply using

with(aVeryLongNameThatIDontWantToTypeEveryTime) {
  get(abs(get(...), get(...)))
}

does not work: It complains that aVeryLongNameThatIDontWantToTypeEveryTime does not have a companion object. (Of course it doesn't, it's a Java class.)

The only "solution" is to globally import aVeryLongNameThatIDontWantToTypeEveryTime.* in the file which isn't great since the method names are so generic and could collide.

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

0

You can use import alias to give it locally a more convenient name:

import com.example.aVeryLongNameThatIDontWantToTypeEveryTime as MyShortName

If you prefer your scoped solution then I think the only way right now is to specify your own "scope":

object aVeryLongNameThatIDontWantToTypeEveryTimeScope {
    inline fun get() = aVeryLongNameThatIDontWantToTypeEveryTime.get()
    inline fun set() = aVeryLongNameThatIDontWantToTypeEveryTime.set()
    inline fun abs() = aVeryLongNameThatIDontWantToTypeEveryTime.abs()
}

with (aVeryLongNameThatIDontWantToTypeEveryTimeScope) {
    get()
    set()
    abs()
}

Unfortunately, that requires rewriting all functions, including their parameters.

In the future it could be possible to use Java static members similarly to companion objects. There are similar tasks in Kotlin's YouTrack.

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