-2

I'm trying to define an array of numbers with the last being a function. It'll probably be better to give an example:

def myArrayFunc(foo:String, bar:Array[Int[Function1]]) // ?
myArrayFunc("foo", (1,2,3 (myFunction)))

Is this possible using Scala? If so, how?

Thanks in advance.

goo
  • 2,230
  • 4
  • 32
  • 53

3 Answers3

2

Your question as stated is nonsensical, because a function is not a number. But if you meant an array of numbers and also a function, then you can do:

def myArrayFunc(foo:String, bar: Array[Either[Int, Function1[A, B]]])

or if you prefer efficiency over type safety:

def myArrayFunc(foo:String, bar: Array[Any])

But it would really make more sense to do:

def myArrayFunc(foo:String, bar: Array[Int], f: Function1[A, B])

Replace A and B with appropriate types in the above.

wingedsubmariner
  • 13,350
  • 1
  • 27
  • 52
1

Yes it is possible but you cannot use an Array; you need something like a Vector. This is further answered here: How do I create a heterogeneous Array in Scala?

Community
  • 1
  • 1
Anthony G
  • 46
  • 4
0

You can define Array[Int] with an element that is a function as long as the function returns an Int since all elements in a Scala Array must have the same type.

def myArrayFunc(foo:String, bar:Array[Int]) = bar.map(_ + foo) 

scala> def plusOne(i:Int) = i + 1
plusOne: (i: Int)Int

scala> myArrayFunc("foo", Array(1,2,plusOne(2)))
res22: Array[String] = Array(1foo, 2foo, 3foo)
Brian
  • 20,195
  • 6
  • 34
  • 55