我可以覆盖 Scala 中匿名函数的 toString 方法吗? [英] Can I override the toString method of an anonymous function in Scala?

查看:65
本文介绍了我可以覆盖 Scala 中匿名函数的 toString 方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图像这样覆盖 Scala 中匿名函数的 toString:

I tried to override the toString of an anonymous function in Scala like this:

scala> ()=>{def toString="yes"; 1}
res1: () => Int = <function0>

这不起作用 - 我希望 res1 以某种方式为是".

Which does not work - I want res1 to be "yes" somehow.

这可能吗?

推荐答案

你不能用匿名函数文字来做到这一点,你需要扩展 Function trait.例如

You can't do that with anonymous function literals, you will need to extend the Function trait. E.g.

val f = new (() => Int) {
  override def toString = "yes"
  def apply() = 1
}

val f = new Function0[Int] {
  override def toString = "yes"
  def apply() = 1
}

这篇关于我可以覆盖 Scala 中匿名函数的 toString 方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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