为什么返回类型是函数< t,r>在Groovy中忽略?

发布于 2025-01-29 11:54:24 字数 387 浏览 2 评论 0原文

以下简单代码解释了我的困惑:

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)
    }

}

我不知道为什么编译器不抱怨cloture&lt; string&gt;不适合function&lt; float,float&gt;。似乎我可以将任何内容传递给f()

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().

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠檬色的秋千 2025-02-05 11:54:24

以下代码

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)

打印

f: class com.sun.proxy.$Proxy22   true
c: class ConsoleScript10$_run_closure1   false
result 0.1 :: class java.math.BigDecimal
  1. 否则没有类型检查
  2. groovy是动态的 - 除非您指定此(编译)闭合没有实现功能, 。因此,当您将闭合分配到函数时 - Groovy试图通过功能接口委托闭合。即使您使用编译静态...

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...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文