简体   繁体   English

相当于 Scala 中 Python 的 Pass

[英]Equivalent of Python's Pass in Scala

If there is a function that you don't want to do anything with you simple do something like this in Python:如果有一个 function 你不想对你做任何事情,只需在 Python 中做这样的事情:

def f():
    pass

My question is, is there something similar to pass in Scala?我的问题是,在pass中是否有类似的东西?

pass is a syntactic quirk of Python. pass是 Python 的语法怪癖。 There are some cases where the grammar requires you to write a statement, but sometimes you don't want a statement there.在某些情况下,语法要求您编写语句,但有时您不希望在那里编写语句。 That's what pass is for: it's a statement that does nothing.这就是pass的用途:它是一个什么都不做的语句。

Scala never requires you to write a statement, therefore the way to not write a statement is simply to not write a statement. Scala 从不要求您编写语句,因此不编写语句的方法就是不编写语句。

I think () is similar.我认为()是相似的。

scala> def f() = ()
f: ()Unit

scala> f              

scala>

As i understand in python pass is used for not yet implemented cases.据我了解,python pass用于尚未实现的情况。 If you need such thing in scala then use ???如果您在 Scala 中需要这样的东西,请使用??? it's similar to () , but is a function returning Nothing ( def ??? : Nothing = throw new NotImplementedError ) .它类似于() ,但它是一个返回 Nothing ( def ??? : Nothing = throw new NotImplementedError ) 的函数。 Your code will compile, but if you call such a method it will crash with NotImplementedError你的代码会编译,但如果你调用这样的方法,它会因NotImplementedError而崩溃

def foo: ResultType = ???

Generally you can substitute Unit for pass .通常你可以用Unit代替pass You do nothing and the line evaluates to Unit , similar to Java's void , but itself an explicit type.您什么都不做,该行的计算结果为Unit ,类似于 Java 的void ,但它本身是一个显式类型。

// implicit return value of type Unit
def showMsg(msg:Option[String]) = msg match {
    case None => Unit
    case Some(m) => println(m)
}

say you create a stub for a function that will return a string假设您为 function 创建了一个存根,它将返回一个字符串

you can add "" as a placeholder and your function will compile您可以添加""作为占位符,您的 function 将编译

Before

❯ cat TrainingSet.scala
def getCommitMessage(x: String): String = {
}

❯ ./TrainingSet.scala
cat: /Users/lgeoff/.sdkman/candidates/java/current/release: No such file or directory
/Volumes/workplace/migrate_ant_to_gradle/./TrainingSet.scala:59: error: type mismatch;
 found   : Unit
 required: String
  def getCommitMessage(x: String): String = {
                                            ^
one error found

After

❯ cat TrainingSet.scala
def getCommitMessage(x: String): String = {
    ""
}

❯ ./TrainingSet.scala
❯ 

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

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