How to define functional interface with generics in Kotlin?Lambda implementation of interface in kotlinDeclaring Function Literals with generic input parameters in KotlinKotlin interface a java class: Accidental overrideKotlin generic properties issueHow should Kotlin function typealises be documented?Putting generic parameter clazz to RealmQuery when parameter is getting from generic function overritedNested data class in generic interface using KotlinCan a Kotlin class be extended to conform to an Interface (like Swift classes can)?Calling generics method argument in kotlinKotlin generic Collection castInterface as functions in Kotlin

Interview Question - Card betting

Machine Learning Golf: Multiplication

Creating patterns

Does the Milky Way orbit around anything?

Why would "dead languages" be the only languages that spells could be written in?

Did Stalin kill all Soviet officers involved in the Winter War?

Was Wolfgang Unzicker the last Amateur GM?

What's the difference between a type and a kind?

Why do Klingons use cloaking devices?

What is the maximum amount of diamond in one Minecraft game?

Why has Novell never written its own boot loader?

Contributing to a candidate as a Foreign National US Resident?

Data normalization before or after train-test split?

Who pays for increased security measures on flights to the US?

Why does the Batman "crack his knuckles" in "Batman: Arkham Origins"?

In the Seventh Seal why does Death let the chess game happen?

Does a multiclassed wizard start with a spellbook?

Speeding up thousands of string parses

Why is the saxophone not common in classical repertoire?

Can you use a weapon affected by Heat Metal each turn if you drop it in between?

CPA filed late returns, stating I would get money; IRS says they were filed too late

Sleepy tired vs physically tired

What is the addition in the re-released version of Avengers: Endgame?

Why did the "Orks" never develop better firearms than Firelances and Handcannons?



How to define functional interface with generics in Kotlin?


Lambda implementation of interface in kotlinDeclaring Function Literals with generic input parameters in KotlinKotlin interface a java class: Accidental overrideKotlin generic properties issueHow should Kotlin function typealises be documented?Putting generic parameter clazz to RealmQuery when parameter is getting from generic function overritedNested data class in generic interface using KotlinCan a Kotlin class be extended to conform to an Interface (like Swift classes can)?Calling generics method argument in kotlinKotlin generic Collection castInterface as functions in Kotlin






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4















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?










share|improve this question






















  • This question and answer has closely related info: stackoverflow.com/questions/48284994/…

    – Mike Hill
    Mar 25 at 20:08


















4















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?










share|improve this question






















  • This question and answer has closely related info: stackoverflow.com/questions/48284994/…

    – Mike Hill
    Mar 25 at 20:08














4












4








4








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?










share|improve this question














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?







kotlin






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 25 at 19:10









Manuel MaukyManuel Mauky

9451 gold badge9 silver badges15 bronze badges




9451 gold badge9 silver badges15 bronze badges












  • This question and answer has closely related info: stackoverflow.com/questions/48284994/…

    – Mike Hill
    Mar 25 at 20:08


















  • This question and answer has closely related info: stackoverflow.com/questions/48284994/…

    – Mike Hill
    Mar 25 at 20:08

















This question and answer has closely related info: stackoverflow.com/questions/48284994/…

– Mike Hill
Mar 25 at 20:08






This question and answer has closely related info: stackoverflow.com/questions/48284994/…

– Mike Hill
Mar 25 at 20:08













1 Answer
1






active

oldest

votes


















4














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






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55344906%2fhow-to-define-functional-interface-with-generics-in-kotlin%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    4














    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






    share|improve this answer





























      4














      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






      share|improve this answer



























        4












        4








        4







        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






        share|improve this answer















        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







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 27 at 16:53

























        answered Mar 25 at 19:44









        Alexander EggerAlexander Egger

        3,5391 gold badge18 silver badges31 bronze badges




        3,5391 gold badge18 silver badges31 bronze badges


















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55344906%2fhow-to-define-functional-interface-with-generics-in-kotlin%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현