1

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?

13
  • 2
    Why would you want to ? What's the use case ? Commented Mar 13, 2022 at 20:43
  • 3
    I don’t see what the point could be of doing this. You can simply define a top level function with some name. Commented Mar 13, 2022 at 21:14
  • @Tenfour04 the point is same as for every overload Commented Mar 14, 2022 at 12:17
  • @Tenfour04 are you sure you can't overload on the null keyword? pl.kotl.in/PIcDxr-5p Commented Mar 15, 2022 at 14:52
  • 1
    @k314159 I should have said "can't call anything on the null keyword exclusively". If there's some function intended only to be called on null (which still makes no sense to me), then you shouldn't be able to call it on other objects. Commented Mar 15, 2022 at 14:54

1 Answer 1

3

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?.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.