Goldengirl
Goldengirl

Reputation: 967

How to access functions from traits?

I am new to scala and was trying to use trait"s". My code looks something like this.

trait codeHelper {
  def functionCall(x: Integer){

     def valueChecker(){

     /*code to perform the required operation*/

     }
  }
}

I access the trait from my main scala class called "valueCreator" as follows:

 class valueCreator() extends baseClass() with codeHelper {
    val value = valueChecker() 
 }

However this code does not work. I get an error in my main class "valueCreator" saying

"not found: value valueChecker"

Could somebody please tell me how could I access the function from the trait? Thank you in advance for your time

Upvotes: 1

Views: 1887

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

Your definition of valueChecker is inside another method, functionCaller, this is called a nested method. This means that the former method is function local and it is only available to functionCaller. If you want to make it visible at the trait level, you'll need to make it a separate method:

trait CodeHelper {
  def functionCall(x: Int) {
  }

  def valueChecker() {
     /*code to perform the required operation*/
  }
}

Although, it seems like you actually want to call functionCaller perhaps?

class ValueCreator extends BaseClass with CodeHelper {
    val value = functionCaller(2)
}

As a side note, class names in Scala are Pascal Case, meaning the first letter is upper case, not lower case.

Upvotes: 3

Related Questions