【问题标题】:Can I override the toString method of an anonymous function in Scala?我可以覆盖 Scala 中匿名函数的 toString 方法吗?
【发布时间】:2013-08-30 23:10:31
【问题描述】:

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

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

这不起作用 - 我希望 res1 以某种方式“是”。

这可能吗?

【问题讨论】:

    标签: scala


    【解决方案1】:

    您不能使用匿名函数文字来做到这一点,您需要扩展 Function 特征。例如

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

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

    【讨论】:

      猜你喜欢
      • 2012-09-15
      • 2011-05-05
      • 2017-01-23
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多