'How to overload operator for null?
I would like to overload an operator like invoke for null literal.
For example, so I could writen something like
null(1, 2)
Is it possible?
Solution 1:[1]
I wouldn't advise overloading anything on the null literal, as it would cause too much confusion and would have no real-world use case.
However, technically, it's possible:
operator fun Nothing?.invoke() = "hi!"
fun main() {
println(null()) // Works, prints "hi!"
val x = null
println(x()) // Also works.
val y: String? = null
//println(y()) // compilation error
val z: String = ""
//println(z()) // also compilation error
}
It makes use of the fact that the null keyword has the nullable type Nothing?.
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 | k314159 |
