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

331
Visualizações
How to define functional interface with generics in Kotlin?

I'm learning Kotlin and I have some trouble with functions. I'm trying to create something like a functional interface with a generic parameter. In Java I would create something like this:

@FunctionalInterface
public interface Foo<T extends Bar> {
    String something(T arg);
}

Then I can use this somewhere else like this (given that Person extends Bar:


Foo<Person> f = p -> p.toString();

How do you write this with Kotlin?

The first thing I tried was to use type-aliases like this:

typealias Foo<T> = (T) -> String

However, it stopped working when I added the bound to the type parameter:

typealias Foo<T: Bar> = (T) -> String  // Error: Bounds are not allowed on type alias parameters

The second approach was to write an interface that extends the function type:

interface Foo<T: Bar> : (T) -> String

However, now I don't know how to instantiate a lambda function from with this. It works when I create class from it like this:

class Something: Foo<Person> {
    override fun invoke(p: Person): String {
        return p.toString()
    }
}

val f = Something()

But this is a big overhead and I'm sure there has to be a better solution.

So how can I define a function signature that can be reused by many functions that supports generic parameters with bounds in kotlin?

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

0

Most of the time (always?) it is sufficient to define the type of the lambda in the parameter of the function that receives it.

For example:

open class Bar
class Person: Bar()

var f = { p: Person -> p.toString() }

fun <T : Bar> withFoo(block: (T) -> String) { }
fun <T : Bar> otherFoo(block: (T) -> String) { }   

fun main() {
    withFoo(f)
    otherFoo(f)
}

The same way the Kotlin documentation states: "since Kotlin has proper function types, automatic conversion of functions into implementations of Kotlin interfaces is unnecessary and therefore unsupported."

See https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions

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