LoginSignup
0
0

More than 5 years have passed since last update.

How to pass a function as parameter in Kotlin?

Posted at

前書き

この記事はKotlinの関数渡しをどうやって書くかを英語で調べた所、分かりにくいディスカッションや、読みにくく、理解しづらいKotlin公式のリファレンスしかなかったので、できるだけわかりやすく英語で関数渡しをどうやって書くかを説明したものです。

How to pass function as a parameter?

First of all, I know that many of programmer love to write example by using foo() or bar(). However, I hate it because difficult to understand for beginners. So, I will use more practical example which is search function.

search.kt
    fun searchInteger(integers:ArrayList<Int>, moreThan:Int):ArrayList<Int>{
        val result = ArrayList<Int>()
        for(integer in integers){

            if(moreThan <= integer){
                result.add(integer)
            }
        }
        return result
    }

This is a function that find integers which more than moreThan parameter. However this function can search only integer which more than moreThan parameter. So, you can change the integer parameter to function parameter. Such as...

search.kt
    fun searchInteger(integers:ArrayList<Int>, searchCallback: (target:Int) -> Boolean):ArrayList<Int>{
        val result = ArrayList<Int>()
        for(integer in integers){

            if(searchCallback(integer)){
                result.add(integer)
            }
        }
        return result
    }

This function can search all conditions because it is depend on function which passed by searchCallback parameter. Then, you can call this function like...

search.kt
    fun searchMoreThan(integers:ArrayList<Int>, moreThan:Int):ArrayList<Int>{
        return searchInteger(integers, { target -> run{ fun searchMoreThan(integers:ArrayList<Int>, moreThan:Int):ArrayList<Int>{
        return searchInteger(integers, { target -> run{ moreThanTask(target,moreThan) }})
    }

    fun moreThanTask(integer:Int, moreThan:Int):Boolean{
        return (moreThan < integer)
    } }})
    }

    fun moreThanTask(integer:Int, moreThan:Int):Boolean{
        return (moreThan < integer)
    }

You can switch input function to lessThanTask(target,lessThan) which return Boolean that show is input less or not. It will also work.

あとがき

Thanks for reading. Feel free to request editing.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0