Lucas Batistussi
Lucas Batistussi

Reputation: 2343

Is there an easy way to check if some instance is FunctionX in Scala?

Is there any less verbose solution than the solution shown below to check if an instance is Function0/Function1...?

 def isFunction(x: Any) = x match {
        case x: Function0[_] => true
        case x: Function1[_,_] => true
        case x: Function2[_,_,_] => true
        case x: Function3[_,_,_,_] => true
        case x: Function4[_,_,_,_,_] => true
        case x: Function5[_,_,_,_,_,_] => true
        case x: Function6[_,_,_,_,_,_,_] => true
        case x: Function7[_,_,_,_,_,_,_,_] => true
        case x: Function8[_,_,_,_,_,_,_,_,_] => true
        case x: Function9[_,_,_,_,_,_,_,_,_,_] => true
        case x: Function10[_,_,_,_,_,_,_,_,_,_,_] => true
        case x: Function11[_,_,_,_,_,_,_,_,_,_,_,_] => true
        case x: Function12[_,_,_,_,_,_,_,_,_,_,_,_,_] => true
        case x: Function13[_,_,_,_,_,_,_,_,_,_,_,_,_,_] => true
        case x: Function14[_,_,_,_,_,_,_,_,_,_,_,_,_,_,_] => true
        case x: Function15[_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_] => true
        case x: Function16[_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_] => true
        case x: Function17[_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_] => true
        case x: Function18[_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_] => true
        case x: Function19[_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_] => true
        case x: Function20[_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_] => true
        case x: Function21[_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_] => true
        case x: Function22[_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_] => true
        case _ => false
  }


  val x = () => 4

  println(isFunction(x))

Upvotes: 1

Views: 77

Answers (1)

som-snytt
som-snytt

Reputation: 39577

You mean given:

scala> val f = (i: Int, j: Int) => i + j
f: (Int, Int) => Int = <function2>

you want to say

scala> val r = "scala.*Function\\d+".r
r: scala.util.matching.Regex = .*Function\d+

scala> def test(a: Any): Boolean = { def t(k: Class[_]): Boolean = k.getName match { case r() => true case _ => if (k.getSuperclass != null) t(k.getSuperclass) else false } ; t(a.getClass) }
test: (a: Any)Boolean

scala> test(f)
res1: Boolean = true

?

That is on a par with the Tuple test.

Upvotes: 1

Related Questions