0

I have this class

class Tester(round: Int, x: Int, y: Int,sparringPartners:Array[RobotSpecification]) {
  def this(s:Array[RobotSpecification]) = {
    this(5, 800, 600, s)

  }

 def getRandomRobot(eng: RobocodeEngine): Array[RobotSpecification] = {//blabla}
}

and i want to extend doing something like this

class EasyTester() extends Tester(getRandomRobot()){}

Obviously it doesn't work.

Probably the problem is trivial but i'm just recently approaching the OO part of Scala so i never worked with this stuff.

4

1 回答 1

1

If getRandomRobot belongs to Tester logically, but doesn't depend on the state of a tester, you can turn it into a method on a companion object:

object Tester {
    def getRandomRobot(eng: RobocodeEngine): Array[RobotSpecification] = { ... }
}

One way would be just to pass sparringPartners into EasyTester's constructor:

class EasyTester(sparringPartners: Array[RobotSpecification]) extends Tester(sparringPartners) { ... }

import Tester._
val eng = ...
val easyTester = new EasyTester(getRandomRobot(eng))

To make the instantiation simpler than that, EasyTester could have a companion object with an apply method that instantiates it:

import Tester._
object EasyTester {
    def apply(implicit eng: RobocodeEngine) = {
      new EasyTester(getRandomRobot(eng))
   }
}

implicit val eng: RobocodeEngine = ...
val easyTester = EasyTester
于 2013-03-30T19:15:49.263 回答