简体   繁体   English

Scala匿名函数的语法更好?

[英]Better syntax for Scala anonymous function?

Experimenting with Scala... I'm trying to define something analogous to the "@" hack in PHP (which means, ignore any exception in the following statement). 尝试使用Scala ...我试图在PHP中定义类似于“@”hack的东西(这意味着,忽略以下语句中的任何异常)。

I managed to get a definition that works: 我设法得到一个有效的定义:

def ignoreException(f: () => Unit) = {
      try {
        f();
      }
      catch {
        case e: Exception => println("exception ignored: " + e);
      }
    }

And use it like this: 并像这样使用它:

ignoreException( () => { someExceptionThrowingCodeHere() } );

Now here is my question... Is there anyway I can simplify the usage and get rid of the () =>, and maybe even the brackets? 现在这里是我的问题......无论如何,我可以简化用法并摆脱()=>,甚至括号?

Ultimately I'd like the usage to be something like this: 最终我希望用法是这样的:

`@` { someExceptionThrowingCodeHere(); }

@ is reserved in Scala (for pattern matching), but would you accept @@ ? 在Scala中保留@ (用于模式匹配),但是你会接受@@吗?

scala> def @@(block: => Unit): Unit = try {
  block
} catch {
  case e => printf("Exception ignored: %s%n", e)
}   
$at$at: (=> Unit)Unit

scala> @@ {
  println("before exception")
  throw new RuntimeException()
  println("after exception")
}
before exception
Exception ignored: java.lang.RuntimeException

I'm not convinced this is a good idea, however ☺ 我不相信这是个好主意,不过☺

You don't have to use a function as your parameter, a "by-name" parameter will do: 您不必使用函数作为参数,“by-name”参数将执行以下操作:

def ignoreException(f: =>Unit) = {
  try {
    f
  }
  catch {
    case e: Exception => println("exception ignored: " + e)
  }
}

ignoreException(someExceptionThrowingCodeHere())

Eric. 埃里克。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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