'Why is the return type in Function<T, R> ignored in Groovy?

The following simple code explains my confusion:

class Main {

    static void f(Function<Float, Float> c) {
        println(c.apply(0.0f))
    }

    static void main(String[] args) {
        Closure<String> c = {"hi"}
        f(c)
    }

}

I have no idea why the compiler does not complain that Closure<String> is not appropriate for Function<Float, Float>. Seems that I can pass anything to f().



Solution 1:[1]

the following code

import java.util.function.*

def c = {"result $it :: ${it.getClass()}"}
Function<Float, Float> f = c

println "f: ${f.getClass()}   ${f instanceof Function}"
println "c: ${c.getClass()}   ${c instanceof Function}"

println f.apply(0.1)

prints

f: class com.sun.proxy.$Proxy22   true
c: class ConsoleScript10$_run_closure1   false
result 0.1 :: class java.math.BigDecimal
  1. groovy is dynamic - there is no type check unless you specify this (CompileStatic)
  2. closure does not implement function. so, when you are assigning closure into function - groovy tries to delegate closure through a function interface. it will be dynamic even if you use compile static...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 daggett