In: Computer Science
In a package named "oop" create a Scala class named "Score" with the following: • A constructor that takes an Int and stores it in a member variable named score • A method named scoreGoal that takes no parameters and has return type Unit that increments the score by 1 • A method named isWinner that takes a Score object as a parameter and returns a Boolean. The method returns true if this instances score is strictly greater than the inputs objects score, false otherwise
In a package named "tests" create a Scala class named "TestScore" as a test suite that tests all the functionality listed above
Note:
Please use below scala version and package to run the code, update your build.sbt with below code.
name := "scala-interview" version := "0.1" scalaVersion := "2.11.7" libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.8" libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.8" % "test"
Scala code(Score.scala):
package oop class Score(x:Int) { //Assigning to member variable var score:Int = x //Increase score value by 1 when player hits goal def scoreGoal: Unit = score +=1 //Winner check def isWinner = if(score > x) true else false } object oop { def main(args: Array[String]): Unit = { //Initialize Score class for player1 and player2 val player1 = new Score(0) val player2 = new Score(0) //player 1 score a goal player1.scoreGoal // Results println("Player1 score result: " + player1.isWinner) println("Player2 score result: " + player2.isWinner) } }
Code with result:
Test cases:
package tests import org.scalatest._ import oop.Score class TestScore extends FlatSpec with Matchers { val player1 = new Score(0) val player2 = new Score(0) "Player2 hits NO goal" should "Initial goal is 0 and final score also 0 1.Winner is false" in { player1.isWinner should be (false) } "Player1 hits first goal" should "Initial goal is 0 and after the goal its 1.Winner is true" in { player1.scoreGoal player1.isWinner should be (true) } "Player2 hits NO goal" should "Initial goal is 0 and score also 0 .Winner is false" in { player2.isWinner should be (false) } "Player2 hits a goal" should "Initial goal is 0 and score 1 .Winner is True" in { player2.scoreGoal player2.isWinner should be (true) } }
Test case code screenshot:
Testcases result summary: