'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:
def f():
pass
My question is, is there something similar to pass in Scala?
Solution 1:[1]
pass is a syntactic quirk of 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.
Scala never requires you to write a statement, therefore the way to not write a statement is simply to not write a statement.
Solution 2:[2]
I think () is similar.
scala> def f() = ()
f: ()Unit
scala> f
scala>
Solution 3:[3]
As i understand in python pass is used for not yet implemented cases. If you need such thing in scala then use ??? it's similar to (), but is a function returning Nothing (def ??? : Nothing = throw new NotImplementedError) . Your code will compile, but if you call such a method it will crash with NotImplementedError
def foo: ResultType = ???
Solution 4:[4]
Generally you can substitute Unit for pass. You do nothing and the line evaluates to Unit, similar to Java's void, but itself an explicit type.
// implicit return value of type Unit
def showMsg(msg:Option[String]) = msg match {
case None => Unit
case Some(m) => println(m)
}
Solution 5:[5]
say you create a stub for a function that will return a string
you can add "" as a placeholder and your function will compile
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
?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jörg W Mittag |
| Solution 2 | Brian |
| Solution 3 | Remis Haroon - ???? |
| Solution 4 | climmunk |
| Solution 5 | Geoff Langenderfer |
