如何开发宏来短路零?

Mic*_*lak 4 macros scala

在斯卡拉,如果我有

hub = myBicycle.getFrontWheel.getHub()
Run Code Online (Sandbox Code Playgroud)

并且可能前轮缺失,即myBicycle.getFrontWheel() == null,我只想在这种情况下hub被分配null,表达这种情况最简洁的方式是什么?

我现在不得不这样做

hub = if (myBicycle.getFrontWheel() == null) null else myBicycle.getFrontWheel.getHub()
Run Code Online (Sandbox Code Playgroud)

当访问者链更长时,它会变得更糟.

不熟悉Scala宏,我想知道是否有可能编写一个Scala宏以某种方式捕获方法名称并仅在对象引用为非null时才应用它?

ghi*_*hik 5

实际上,我最近编写了这样一个宏,其灵感来自于Scala中关于null安全解除引用的问题.顺便说一句,这是一个与此问题非常类似的问题,并且包含了一个关于你可以做些什么来实现这一目标的长期讨论,包括使用Option,捕捉NPE的奇特方法等.

我写的一些关于宏的评论(来源包括在下面):

  • 它返回一个Option,它将None在某个时刻出现空取消引用.
  • 它使用if-else将每个成员访问点转换为空值保护访问,并None在前缀时返回null.
  • 它有点复杂,我想象它...
  • 有些极端情况不起作用,我所知道的就是使用getClass方法 - 这是由编译器特别针对其返回类型处理的.
  • 隐式转换可能存在不一致.想象一下,你有一个表达式,a.bb通过一个隐式转换来实现,所以有效地说,这个表达式是这样的conv(a).b.现在,问题出现了:我们应该检查是否anull,conv(a)是否null或两者兼而有之?目前,我的宏检查仅anull因为它似乎多了几分自然的我,但是这可能不是在某些情况下所需的行为.此外,在我的宏中检测隐式转换是一个小问题,在这个问题中描述.

宏:

def withNullGuards[T](expr: T): Option[T] = macro withNullGuards_impl[T]

def withNullGuards_impl[T](c: Context)(expr: c.Expr[T]): c.Expr[Option[T]] = {
  import c.universe._

  def eqOp = newTermName("==").encodedName
  def nullTree = c.literalNull.tree
  def noneTree = reify(None).tree
  def someApplyTree = Select(reify(Some).tree, newTermName("apply"))

  def wrapInSome(tree: Tree) = Apply(someApplyTree, List(tree))

  def canBeNull(tree: Tree) = {
    val sym = tree.symbol
    val tpe = tree.tpe

    sym != null &&
      !sym.isModule && !sym.isModuleClass &&
      !sym.isPackage && !sym.isPackageClass &&
      !(tpe <:< typeOf[AnyVal])
  }

  def isInferredImplicitConversion(apply: Tree, fun: Tree, arg: Tree) =
    fun.symbol.isImplicit && (!apply.pos.isDefined || apply.pos == arg.pos)

  def nullGuarded(originalPrefix: Tree, prefixTree: Tree, whenNonNull: Tree => Tree): Tree =
    if (canBeNull(originalPrefix)) {
      val prefixVal = c.fresh()
      Block(
        ValDef(Modifiers(), prefixVal, TypeTree(null), prefixTree),
        If(
          Apply(Select(Ident(prefixVal), eqOp), List(nullTree)),
          noneTree,
          whenNonNull(Ident(prefixVal))
        )
      )
    } else whenNonNull(prefixTree)

  def addNullGuards(tree: Tree, whenNonNull: Tree => Tree): Tree = tree match {
    case Select(qualifier, name) =>
      addNullGuards(qualifier, guardedQualifier =>
        nullGuarded(qualifier, guardedQualifier, prefix => whenNonNull(Select(prefix, name))))
    case Apply(fun, List(arg)) if (isInferredImplicitConversion(tree, fun, arg)) =>
      addNullGuards(arg, guardedArg =>
        nullGuarded(arg, guardedArg, prefix => whenNonNull(Apply(fun, List(prefix)))))
    case Apply(Select(qualifier, name), args) =>
      addNullGuards(qualifier, guardedQualifier =>
        nullGuarded(qualifier, guardedQualifier, prefix => whenNonNull(Apply(Select(prefix, name), args))))
    case Apply(fun, args) =>
      addNullGuards(fun, guardedFun => whenNonNull(Apply(guardedFun, args)))
    case _ => whenNonNull(tree)
  }

  c.Expr[Option[T]](addNullGuards(expr.tree, tree => wrapInSome(tree)))
}
Run Code Online (Sandbox Code Playgroud)

编辑

这是一段额外的代码,使语法更好:

def any2question_impl[T, R >: T](c: Context {type PrefixType = any2question[T]})(default: c.Expr[R]): c.Expr[R] = {
  import c.universe._

  val Apply(_, List(prefix)) = c.prefix.tree
  val nullGuardedPrefix = withNullGuards_impl(c)(c.Expr[T](prefix))
  reify {
    nullGuardedPrefix.splice.getOrElse(default.splice)
  }
}

implicit class any2question[T](any: T) {
  def ?[R >: T](default: R): R = macro any2question_impl[T, R]
}
Run Code Online (Sandbox Code Playgroud)

最后,您可以使用以下代码:

val str1: String = "hovercraftfullofeels"
val result1 = str1.substring(3).toUpperCase ? "THERE WAS NULL"
println(result1) // prints "ERCRAFTFULLOFEELS"

val str2: String = null
val result2 = str2.substring(3).toUpperCase ? "THERE WAS NULL"
println(result2) // prints "THERE WAS NULL"
Run Code Online (Sandbox Code Playgroud)