0

Hello and thanks in advanced.

I'm attempting to create an auxiliary constructor in Scala. This auxiliary constructor takes in an array of strings, and then calls the primary constructor (which takes a single string) on each of the strings in the array.

The complete code is the following:

class CommentEvaluator(comment:String){

     def this(comments:Array[String]) = {
       for(i <- 0 until comments.length){
        this(comments(i))
        println(comments(i) + "passed to constructor")
      }
    }
}

I'm getting a compile error on the line this(comments(i))

From what I've read, this error is sometimes caused by incorrect parameter type inside a function call. In this case, my primary constructor clearly takes a string as parameter.

It seems that I can also do this(comments(0))outside of the loop but when I try to do it within the loop, again I get this "Application does not take parameters error."

I'm new to Scala and would appreciate any suggestions.

Thanks!

xvm
  • 1
  • First of all, logically what you trying to achieve is not possible. 'this' method calls when a user tries to construct a new object. However, inside that method, you are trying to construct multiple objects which don't make any sense. 'this' method will not return anything so even if it were possible it was useless. However, if you really want to get multiple objects by passing multiple comments, you can use companion object. Here is the code : – aks Jul 06 '17 at 05:04
  • class CommentEvaluator(comment:String) object CommentEvaluator{ def apply(comment:String) = new CommentEvaluator(comment) def apply(comments:List[String]): List[CommentEvaluator] = { comments.map(comment => new CommentEvaluator(comment)) } } – aks Jul 06 '17 at 05:06

0 Answers0