Donbeo
Donbeo

Reputation: 17617

scala define type in a package

This question has already been asked but I still need some clarification. I want to define a type in a package and then use it in the classes of the package.

This is what I wrote:

/**
  * Created by donbeo on 28/12/15.
  */
package tiktaktoe

package object tiktaktoe {

  type Pos = (Int, Int)

}

class Board {

  val board = List.fill(3, 3)(0)

  def isValidPosition(pos:Pos):Boolean = true 

}


class Player {

  def nextMove(pos:Pos):Board = new Board

}

But Pos does not seems to be recognized. What is the right way to write it?

Upvotes: 1

Views: 51

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

The way you've declared it has it so that package object tiktaktoe is inside package tiktaktoe. So the fully-qualified package name is tiktaktoe.tiktaktoe.Pos. Generally, package objects are declared in a separate file called package.scala, and they should be declared in the package above the desired target (in this specific case, nothing).

If you were to have a longer package name:

package.scala:

package longer.name

package object tiktaktoe {

  type Pos = (Int, Int)

}

Board.scala:

package longer.name.tiktaktoe

class Board {

  val board = List.fill(3, 3)(0)

  def isValidPosition(pos:Pos):Boolean = true 

}

Upvotes: 4

Related Questions