【问题标题】:Can I define a nameless method in a Scala class?我可以在 Scala 类中定义无名方法吗?
【发布时间】:2023-04-10 10:42:01
【问题描述】:

这可以达到吗?如果是,请更正我的 Foo 声明语法。

class Foo (...) { ... def /* the nameless method name implied here */ (...) : Bar = new Bar (...) ... } class Bar (...) { ... } val foo : Foo = new Foo (...) val fooBar : Bar = foo (...)

【问题讨论】:

    标签: class scala syntax methods


    【解决方案1】:

    你应该使用 apply 方法:

    class Foo (y: Int) {
      def apply(x: Int) : Int = x + y
    }
    
    
    val foo : Foo = new Foo (7)
    
    val fooBar  = foo (5)
    
    println(fooBar)
    

    然后运行代码:

    bash$ scala foo.scala 
    12
    

    【讨论】:

      【解决方案2】:

      我认为使用 'apply' 为你的方法名称应该像这样工作。

      【讨论】:

        【解决方案3】:

        您可以扩展Function0[Bar] 并实现def apply: Bar。见Function0

         object Main extends Application {
           val currentSeconds = () => System.currentTimeMillis() / 1000L
           val anonfun0 = new Function0[Long] {
             def apply(): Long = System.currentTimeMillis() / 1000L
           }
           println(currentSeconds())
           println(anonfun0())
         }
        

        【讨论】:

        • 为了澄清,这里显示了两个定义。 currentSeconds 这是一个匿名函数,基本上是anonfun0 所示定义的语法糖
        猜你喜欢
        • 2011-05-23
        • 2016-07-11
        • 1970-01-01
        • 2019-11-04
        • 1970-01-01
        • 2014-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多