Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type inference for higher order functions with generic return types

Tags:

kotlin

The following example is perfectly legal in Kotlin 1.3.21:

fun <T> foo(bar: T): T = bar

val t: Int = foo(1) // No need to declare foo<Int>(1) explicitly

But why doesn't type inference work for higher order functions?

fun <T> foo() = fun(bar: T): T = bar

val t: Int = foo()(1) // Compile error: Type inference failed...

When using higher order functions, Kotlin forces the call site to be:

val t = foo<Int>()(1)

Even if the return type of foo is specified explicitly, type inference still fails:

fun <T> foo(): (T) -> T = fun(bar: T): T = bar

val t: Int = foo()(1) // Compile error: Type inference failed...

However, when the generic type parameter is shared with the outer function, it works!

fun <T> foo(baz: T) = fun (bar: T): T = bar

val t: Int = foo(1)(1) // Horray! But I want to write foo()(1) instead...

How do I write the function foo so that foo()(1) will compile, where bar is a generic type?

like image 983
breandan Avatar asked Feb 21 '19 04:02

breandan


People also ask

Can higher-order functions be used as return types?

Higher order functions take other functions as parameters or return a function as a result. This is possible because functions are first-class values in Scala.

Which of the following is a higher-order function?

The map function is one of the many higher-order functions built into the language. sort, reduce, filter, forEach are other examples of higher-order functions built into the language.

What is higher-order function in Scala with example?

It means that functions can be passed as arguments to other functions, and functions can return other functions. The map function is a classic example of a higher order function. 1. val list = List(1,2,3) Let's define a function that doubles each value that is given to it.

What is higher-order function in Python example?

Higher-order functions are functions that take a function as a parameter and/or return a function as an output. A few useful higher-order functions are map() , filter() , and reduce() . map() and filter() are built-in functions, whereas reduce() is contained in functools() module.


1 Answers

I am not an expert on how type inference works, but the basic rule is: At the point of use the compiler must know all types in the expression being used.

So from my understanding is that:

foo() <- using type information here

foo()(1) <- providing the information here

Looks like type inference doesn't work 'backward'

    val foo = foo<Int>()//create function
    val bar = foo(1)//call function
like image 130
PolishCivil Avatar answered Nov 03 '22 01:11

PolishCivil