How would I override a function in Scala with another function?

In scala I have this function:

def handleCollision {
    walls.foreach(w => if (curPlayer.intersects(w)) {
            curPlayer.setLocation(playerStartPos._1, playerStartPos._2)
            updateLives(-1)
        })
    obstacles.foreach(o => if (curPlayer.intersects(o)) {
            curPlayer.setLocation(playerStartPos._1, playerStartPos._2)
            updateLives(-1)
        })
} // End "handleCollision"

What I want to do is when a player hits the key "c" in my match statement:

 case 'c' => 

I want it to call this function and override the above function so that it does not work anymore:

def cheatKey {
    walls.foreach(w => if (curPlayer.intersects(w)) {
            updateLives(+0)
        })
    obstacles.foreach(o => if (curPlayer.intersects(o)) {
            updateLives(+0)
        })
 }

Thank you

Answers


You could start by declaring a var to hold the default function for handling a collision like so:

var collisionFunction = () => {
  curPlayer.setLocation(playerStartPos._1, playerStartPos._2)
  updateLives(-1)    
}

Then, your handleCollision function would be changed to this:

def handleCollision { 
  walls.foreach(w => if (curPlayer.intersects(w)) {
    collisionFunction()
  })

  obstacles.foreach(o => if (curPlayer.intersects(o)) {
    collisionFunction()
  })
}

Then, when you hit your cheat condition, you would update collisionFunction like so:

collisionFunction = () => {
  updateLives(+0)
}

This is a little crude as it has a mutable variable for the function swapping, but it would work for what you are looking to do.


Need Your Help

How do I access an in-memory database using Sequel.sqlite?

ruby sqlite sequel in-memory-database

I am accessing the in-memory database using Sequel in a Sinatra application. I want to access the in-memory database used in my application from the command line on my local host, as well as Heroku...

WordPress plugin include css from subdirectory

wordpress plugins

I have a question about including an css file (wordpress) for my metabox styling in the backend. I have read the ebook "Building Wordpress Theme From Scratch" from Rockable. They had the following

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.