How to add any action to the constructor?

The naive question that I consider, but all I find is just to call other constructors from the constructors. I need to call a method. My class (start):

class ScopedIterator[T](val iter : Iterator[T]) { private var had_next : Boolean; private var value : T; moveNext(); ... 

therefore, I would like to have a constructor with a single argument, and in such a constructor, call the moveNext method. It's all.

When I compile the code, I get an error:

error: abstract member may not have a private modifier

private var had_next: Boolean;

and the same for value .

I changed it to:

 class ScopedIterator[T] { private var had_next : Boolean; private var value : T; private var iter : Iterator[T]; def this(it : Iterator[T]) = { iter = it; moveNext(); } ... 

But now I get the error message "iter = it":

error: 'this' is expected, but an identifier is found.

iter = it;

How to write such a constructor in Scala?

+7
source share
2 answers

The first problem is that your had_next and value definitions are abstract: these members do not have the right side.

Try instead:

 class ScopedIterator[T](val iter : Iterator[T]) { private var had_next : Boolean = _ private var value : T = _ ... } 

Here, _ means "uninitialized default value." For example, for a console, the following works in the console:

 class ScopedIterator[T](val iter : Iterator[T]) { private var had_next : Boolean = _ private var value : T = _ init() def init() : Unit = { println("init !") } } scala> new ScopedIterator(List(1,2,3).toIterator) init ! resN: ScopedIterator[Int] = ... 

The second problem ("'this' expected ...") arises because in Scala helper constructors should always call another constructor as their first statement. For example, your constructor may begin with this() , for example. See Section 6.7 in Programming in Scala for more information.

+18
source

The default constructor is the one you define when you declare your class

Example:

 class greeting(name:String) { ... } 

You can also define a default constructor to not accept any parameters, as in your code

 class greeting { ... } 

Then you can add additional constructors. All constructors added to the class must call another constructor as the first constructor statement. If you omit this, you will get "this expected but found identifier."

Let's look at an example:

 class classconstructor { var iter:Int = 0 def this(it:Int) = { this() iter = it; moveNext(); } def moveNext() = { println(iter) } } object App { def main(args:Array[String]) { val x = new classconstructor() val y = new classconstructor(200) } } 

In the above code, new classconstructor () does nothing, because an empty constructor has no body. and also new classconstructor (200) executes an empty constructor + new, where you can add additional code, for example, calling the moveNext () method. In this case, it prints 200 on the console.

+6
source

All Articles