如何比较 Scala 函数值的相等性 [英] How to compare Scala function values for equality

查看:49
本文介绍了如何比较 Scala 函数值的相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何比较两个 Scala 函数值的相等性.用例是我有一个函数列表,其中列表可以包含重复项,并且我只想执行每个函数一次.

How can you compare two Scala function values for equality. The use case is that I have a list of functions where the list can contain duplicates and I only want to execute each function once.

如果我有:

scala> object A {
     |   def a {}
     | }
defined module A

scala> val f1 = A.a _
f1: () => Unit = <function0>

scala> val f2 = A.a _
f2: () => Unit = <function0>

如果我尝试将函数与 ==eq 进行比较,在这两种情况下我都会得到 false:

If I try to compare the function with either == or eq, I will get false in both cases:

scala> f1 == f2
res0: Boolean = false

scala> f1 eq f2
res1: Boolean = false

推荐答案

简短回答:不可能.

更长的答案:您可以拥有某种函数工厂来确保相同"的函数实际上是同一个对象.不过,根据您的应用程序的架构,这可能不可行.

Longer answer: You could have some kind of function factory that ensures that "identical" functions are acutally the same object. Depending on the architecture of your application, that might not be feasible though.

这篇关于如何比较 Scala 函数值的相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆