How can i write a isFunction function in scala, so that this works:
def isFunction(x:Any) = /* SomeCode */
println(isFunction(isFunction _)) //true
println(isFu
I am not a special fan of your solution and I agree with Daniel Sobral comment. If I had to implement it I would do that in a type safe way, through implicit conversion
trait IsFunctionable {
def isFunction : Boolean
}
object IsFunctionable {
object IsFunction extends IsFunctionable {
def isFunction = true
}
object IsNotFunction extends IsFunctionable {
def isFunction = false
}
implicit def function0ToIsFunctionable[A<:Function0[_]](a:A):IsFunctionable = IsFunction
implicit def function1ToIsFunctionable[A<:Function1[_,_]](a:A):IsFunctionable = IsFunction
implicit def function2ToIsFunctionable[A<:Function2[_,_,_]](a:A):IsFunctionable = IsFunction
// and so on
implicit def anyToIsFunctionable[A](a:A):IsFunctionable = IsNotFunction
}
And now you can happily test in the repl:
scala> import IsFunctionable._
import IsFunctionable._
scala> val a: Int => Int = _ * 2
a: Int => Int =
scala> val b: (Int,Int) => Int = (_*_)
b: (Int, Int) => Int =
scala> a(3)
res0: Int = 6
scala> b(2,4)
res3: Int = 8
scala> a.isFunction
res4: Boolean = true
scala> b.isFunction
res5: Boolean = true
scala> "Hello".isFunction
res6: Boolean = false