如何使用repl创建在object中定义的case类的实例

时间:2017-09-07 07:01:48

标签: scala loading read-eval-print-loop

在Scala repl中加载方法后,我在创建case类的实例时遇到了问题。

这是代码。

object Game {
    def main(args: Array[String]) {
        val player1 = new Player("monu", 344)
        val player2 = new Player("pankaj", 78)
        declareWinner(player1, player2)
    }

    def printWinner(p: Player): Unit =
        println(p.name + " is the winner!")

    def declareWinner(p1: Player, p2: Player): Unit =
        if (p1.score > p2.score) printWinner(p1)
        else printWinner(p2)

case class Player(name: String, score: Int)
}

输出:

scala> :paste Game.scala
Pasting file Game.scala...
defined object Game

scala> val bob = Player("Bob",8 )
<console>:7: error: not found: value Player
       val bob = Player("Bob",8 )

但是如果我删除对象定义并且只是将代码保存在代码中就没有问题:

def main(args: Array[String]) {
        val player1 = new Player("monu", 344)
        val player2 = new Player("pankaj", 78)
        declareWinner(player1, player2)
    }

    def printWinner(p: Player): Unit =
        println(p.name + " is the winner!")

    def declareWinner(p1: Player, p2: Player): Unit =
        if (p1.score > p2.score) printWinner(p1)
        else printWinner(p2)

case class Player(name: String, score: Int)

输出:

scala> :paste Game.scala
Pasting file Game.scala...
main: (args: Array[String])Unit
printWinner: (p: Player)Unit
declareWinner: (p1: Player, p2: Player)Unit
defined class Player

scala> val bob = Player("Bob",8 )
bob: Player = Player(Bob,8)

如果有人可以建议一种方法来解决第一种情况的问题,那将会非常有用。

2 个答案:

答案 0 :(得分:0)

在第一个示例中,您需要使用Game.Player而不仅仅是Player,因为它是Game的内部类。

答案 1 :(得分:0)

解决问题的第一种方法是使用Player访问Game.Player案例类,作为:
val bob = Game.Player("Bob",8 )

第二种方法是先使用import Game._import Game.Player导入课程,然后按照val bob = Player("Bob",8 )之前的步骤执行代码。