How can i write a isFunction function in scala, so that this works:
def isFunction(x:Any) = /* SomeCode */
println(isFunction(isFunction _)) //true
println(isFu
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))