How to write the function isFunction in scala?

后端 未结 3 1691
长发绾君心
长发绾君心 2021-01-29 02:48

How can i write a isFunction function in scala, so that this works:

def isFunction(x:Any) = /* SomeCode */

println(isFunction(isFunction _)) //true
println(isFu         


        
3条回答
  •  感情败类
    2021-01-29 03:37

    In scala you can view Functions as just objects that have a public apply method. I am not familiar with the new scala 2.10 reflection api, but you can always use traditional java way as:

    def isFunction(x:Any) = x.getClass.getMethods.map(_.getName).exists{name => 
      name == "apply" || name.startsWith("apply$")
    }
    
    val set = Set(1, 2)
    val str = "abc"
    val func = { _:Int=> 1 }
    val map = Map(1 -> 2)
    val tuple = 1->2
    val obj = new { def apply = 1 }
    val obj2 = new { private def apply = 2 } 
    
    assert(isFunction(set))
    assert(!isFunction(str))
    assert(isFunction(func))
    assert(isFunction(map))
    assert(!isFunction(tuple))
    assert(isFunction(obj))
    assert(!isFunction(obj2))
    

提交回复
热议问题