简体   繁体   中英

Scala: How to declare two interdependent classes

So basically I'm starting scala and I'm trying to build a simple RPG script to get accustomed to the language. The first problem I encountered is how do I declare a class Character and a class Ennemy, knowing each have methods using instances of the other class as arguments. I haven't encountered this problem in other languages (Or they have a way of saying: Hey I'm using this other class but don't instantiate anything unless you're called), here in Scala I have the following error: not found: type Ennemy.

I guess there is a key word to use somewhere but I just can't find it.

Thanks

Edit: Sorry I didn't incorporate the code, BUt basically I stripped it down to this:

class Character {
  var name = ""
  def slain(e:Ennemy) = println(this.name + " has slain ennemy " + e.name)
} 

class Ennemy {
  var name = ""
  def slain(c:Character) = println(this.name + " has slain character " +     c.name)
}

And the code still doesn't compile and return the mentioned error.

If you're in the scala repl, you need to define them at the same time to avoid this. This is because each expression is run one at a time, and if you can't reference something that isn't defined yet.

Note that this is not a problem for classes defined in .scala source files.

You can use :paste to define multiple things at once.

scala> :paste
// Entering paste mode (ctrl-D to finish)

class Character {
  var name = ""
  def slain(e:Ennemy) = println(this.name + " has slain ennemy " + e.name)
} 

class Ennemy {
  var name = ""
  def slain(c:Character) = println(this.name + " has slain character " +     c.name)
}

// Exiting paste mode, now interpreting.

defined class Character
defined class Ennemy

Other notes:

  • It's spelt Enemy
  • You could consider giving both of these a parent class

trait Entity {
  var name = ""
  def slain(e: Entity) = println(this.name + " has slain enemy " + e.name)
}
class Character extends Entity
class Enemy extends Entity

This does mean that characters and enemies can kill their own kind. There's ways you can define it differently to avoid this, but I'll omit them since I think it's more complicated than you need right now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM