This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
- Clojure
- Clojure
- C++
- C++
- C#
- Dart
- Fortran
- Go
- JS
- Java
- Java
- Java
- Lua
- PHP
- Pascal
- Perl
- Python
- Ruby
- Rust
- VB
(defn f [& [x]]
(if (integer? x)
(println "Present" x)
(println "Not present")))
Optional argument with positional parameters
(defn f
([] (println "Not present"))
([x] (println "Present" x)))
Optional argument with pattern matching
void f(std::optional<int> x = {}) {
std::cout << (x ? "Present" + std::to_string(x.value()) : "Not Present");
}
c++ 17
void f(std::optional<int> x = {}) {
if (x) {
std::cout << "Present" << x.value();
} else {
std::cout << "Not present";
}
}
c++ 17
void f(int? x = null)
{
Console.WriteLine(x.HasValue ? $"Present {x}" : "Not Present");
}
Optional arguments in the CLR are honoured by the calling language by substituting the specified default value in place of an omitted argument. The callee thus cannot distinguish between an omitted argument and a passed argument with the same value as the specified default. Nullable<int> is used here because int is a value type.
func f(x ...int) {
if len(x) > 0 {
println("Present", x[0])
} else {
println("Not present")
}
}
Go does not have optional arguments, but to some extend, they can be mimicked with a variadic parameter.
x is a variadic parameter, which must be the last parameter for the function f.
Strictly speaking, x is a list of integers, which might have more than one element. These additional elements are ignored.
x is a variadic parameter, which must be the last parameter for the function f.
Strictly speaking, x is a list of integers, which might have more than one element. These additional elements are ignored.
void f() { set(null); }
void f(int x) { set(x); }
private void set(Integer t) {
if (t != null) out.println("Present");
else out.println("Not present");
}
In Java, "overloading" a method is the typical way to create an optional parameter.
void f(int ... x) {
if (x.length != 0) out.println("Present");
else out.println("Not present");
}
"... The method can then be called with any number of that parameter, including none."
fn f(x: Option<()>) {
match x {
Some(x) => println!("Present {}", x),
None => println!("Not present"),
}
}