简体   繁体   中英

How can I get around using Null in this situation? (Scala and Akka)

In order to generalize a function, I found myself using null. But I can't figure out how to refactor to remove it. Here's the code snip:

trait ContextSwitch {
  def appropriateContext(implicit context: ActorContext = null, system: ActorSystem = null): ActorRefFactory = {

    val either: Either[ActorContext, ActorSystem] = if (context != null) Left(context) else Right(system)
    val refProvider = either.fold[ActorRefFactory](ac => ac, as => as)
    refProvider
  }
}

The idea is that I am now able to call this:

appropriateContext.actorOf(Props[Actor])

and it works no matter the context. Which makes my other functions that depend on it testable (since tests are at the system level while the functions are usually deployed on actors where only context is available)

The function works, but how can I get rid of the nulls?

Why not just:

trait ContextSwitch {
  def appropriateContext(implicit factory: ActorRefFactory) = factory
}

?

This way you simply let the scala compiler choose either ActorContext or ActorSystem for you, whichever is visible in current context.

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