Function Types
Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 27 of 63.
A function type describes the argument types in parentheses, followed by -> and the result type. For example, (Int) -> Boolean accepts an integer and returns a Boolean. When the type is known, a one-parameter lambda can refer to its argument as it.
Inside main:
val isEven: (Int) -> Boolean = { it % 2 == 0 }
println(isEven(6))The function value tests whether the remainder after division by two is zero.
Function types specify inputs and a result; it is available for one implicit lambda parameter.
Challenge
MediumComplete checkPositive with parameters value: Int. Declare a variable check of type (Int) -> Boolean whose lambda tests whether its input is strictly positive. Return check(value).
Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.
Return a value of type Boolean. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.
Try it yourself
fun checkPositive(value: Int): Boolean {
// Write your solution here.
return false
}
fun main() {
val value = readln().toInt()
println(checkPositive(value))
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
4Nested Collections
Lists of ListsTraversing RowsRow SummariesFlattening Nested ListsRecap - Seating Rows7Collection Pipelines
Transforming with MapFiltering ValuesTesting Collection RulesAccumulating with FoldRecap - Approved Totals5Project - Contact Book
Save ContactsFind Contacts6Function Values
Writing LambdasFunction TypesPassing FunctionsCaptured VariablesRecap - Configurable ScorePractice on your own: Kotlin playground