代码之家  ›  专栏  ›  技术社区  ›  Jean-Philippe Pellet

如何从Scala中的方法获取函数对象?

  •  9
  • Jean-Philippe Pellet  · 技术社区  · 14 年前

    class Simple {
      def doit(a: String): Int = 42
    }
    

    如何在val中存储接受两个参数(目标简单对象,字符串参数)的Function2[Simple,String,Int],并调用doit()返回结果?

    3 回复  |  直到 14 年前
        1
  •  14
  •   sepp2k    14 年前
    val f: Function2[Simple, String, Int] = _.doit(_)
    
        2
  •  12
  •   hbatista    14 年前

    与sepp2k相同,只是使用另一种语法

    val f = (s:Simple, str:String) => s.doit(str)
    
        3
  •  9
  •   retronym    14 年前

    scala> val f = (_: Simple).doit _
    f: (Simple) => (String) => Int = <function1>
    

    遵循一种方法 _

    scala> trait Complex {                        
         |    def doit(a: String, b: Int): Boolean
         | }                                      
    defined trait Complex
    
    scala> val f = (_: Complex).doit _            
    f: (Complex) => (String, Int) => Boolean = <function1>
    

    这包括以下几个方面:§6.23“匿名函数的占位符语法”和§7.1“方法值” Scala Reference