代码之家  ›  专栏  ›  技术社区  ›  Ivan

我可以在scala类中定义一个无名称的方法吗?

  •  2
  • Ivan  · 技术社区  · 14 年前

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

    
    class Foo (...) {
    ...
      def /* the nameless method name implied here */ (...) : Bar = new Bar (...)
    ...
    }
    
    class Bar (...) {
    ...
    }
    
    val foo : Foo = new Foo (...)
    
    val fooBar : Bar = foo (...)
    
    
    
    3 回复  |  直到 14 年前
        1
  •  12
  •   olle kullberg    14 年前

    您应该使用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
  •  4
  •   Felipe    14 年前

    我认为对方法名使用'apply'应该是这样的。

        3
  •  4
  •   Eugene Yokota    14 年前

    你可以延长 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())
     }