igx
igx

Reputation: 4231

Why is the method accepts only one argument?

Looking at this nice Fibonacci implementation :

scala> val fibs = {
          def go(f0: Int, f1: Int): Stream[Int] =
          Stream.cons(f0, go(f1, f0+f1))
           go(0, 1)
          }
fibs: Stream[Int] = Stream(0, ?)

at first look it seems that it accepts two arguments go(f0: Int, f1: Int) but trying that will result TooManyArgumentsException however with one argument it works fine (as it should)

scala> fibs(9)
res23: Int = 34

how can one know the number of arguments fibs should accept ?

Upvotes: 0

Views: 65

Answers (1)

Marth
Marth

Reputation: 24812

fibs is not a method, it's a value of type Stream[Int].

When you write fibs(9), you're calling fibs.apply(9), which, for a Stream, selects an element by its index in the sequence (see here).

This is the same as :

scala> val l = List(1,2,3,4)
l: List[Int] = List(1, 2, 3, 4)

scala> l(2)
res0: Int = 3

Upvotes: 3

Related Questions