开发者

How would I do this in Scala?

开发者 https://www.devze.com 2023-02-08 17:43 出处:网络
So, I just started learning 开发者_运维技巧Scala today, and have been doing fairly well, but I\'ve run into a wall, with this problem...

So, I just started learning 开发者_运维技巧Scala today, and have been doing fairly well, but I've run into a wall, with this problem...

I need to do this in Scala, but am having trouble sorting it out:

final Filter<GameObject> filter = new Filter<GameObject>() {
    public boolean accept(GameObject o) {
        ...
    }
};

ATM I have, but it won't even compile:

val filter = new Filter[GameObject] {
    override def accept(o: GameObject) {
        ...
    }
}

Thanks in advance.

Edit:

Here is the entire object so far:

object Targeter extends LoopTask {

  val filter = new Filter[GameObject] {
    override def accept(o: GameObject) = { true }
  }

  //  Overriding a method in the LoopTask class
  override def loop() = {
    100
  }
}


I think you missed return type:

override def accept(o: GameObject) = {...}

or

override def accept(o: GameObject): Boolean = {...}

These two variants are the same (assuming that you actually return some boolean in the body of this method).


If you define accept method like this:

override def accept(o: GameObject) {...}

then it's the same as:

override def accept(o: GameObject): Unit = {...}

And Unit is equivalent of void in java.


Try to keep any code written in Scala as idiomatic as possible, a handy convertor function will help out here:

def gameFilter[T](fn: T => Boolean) = new Filter[T] {
  override def accept(x: T) = fn(x)
}

Which can then be used as:

val filter = gameFilter[GameObject](_ => true)

Or if you'll only ever filter on GameObjects:

def gameFilter(fn: GameObject => Boolean) = new Filter[GameObject] {
  override def accept(x: GameObject) = fn(x)
}

val filter = gameFilter( _ => true )


override def accept(o: GameObject) {

should be

override def accept(o: GameObject) = {

.. this is a standard beginner's mistake. Also, it would be safer to declare the return type:

override def accept(o: GameObject):Boolean = {

You know I suppose that you can just use a function to replace your filters:

val myFilter : GameObject => Boolean = ...

and then you can just do things like this:

val gameObjects:List[GameObject] = ...
val filteredGameObjects = gameObjects filter myFilter


The "entire object so far" compiles fine assuming the other classes are :

  abstract class LoopTask {
    def loop(): Int
  }

  case class GameObject

  abstract class Filter[T] {
      def accept(o:T):Boolean
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消