kotlin cannot auto import operator funtion such as "+" of other package


#1

For example:

Class common.number.Number.kt:

operator fun Int.plus(other: BigInteger): BigInteger {
return BigInteger(this.toString()).add(other)
}
Class common.test.Test.kt:

var i = 1 + BigInteger(“1”)
Then the Intellij Idea shows an error in class Test.kt. However, if I add the following import, the error disappears:

import common.number.Number.plus
How can I make IntelliJ Idea import this operator function automatically?

more detail see: https://stackoverflow.com/questions/48548592/intellij-idea-kotlin-cannot-auto-import-some-operator-function-such-as

Thanks!


#2

If both files are part of the same package you wont need to import the operator. Also instead of writing import common.number.Number.plus you should be could use import common.number.Number.*. That way you wont have to write the import for each operator.

Except for that there is no way to “skip” imports.


#3

Why not idea suppots using alt+enter to auto import? just like auto import other class, function…


#4

As far as I know idea will give you the option to add the import, as long as it can find the methods/classes/etc.

I just tested it. I had the option to add the import using alt+enter for and operator. So I guess for some reason idea does not “see” you operator. Are you sure your dependencies are working the way they should?


#5

Is it a top-level function? For some reason, IntelliJ doesn’t like to auto import top-level functions. The Http4k library made the decision to use objects and override the invoke operator to overcome this issue.


#6

are you sure your idea shows option for ±*/% operator by alt+enter? Note packages where they define and use are diffrent.
I override these operator between primitive numbers and BigInteger/BigDecimal, if I import them manually, it works, but they can not be imported autoly by idea.


#7

Why IntelliJ doesn’t like to auto import top-level functions, is top-level function a bad design?


#8

It worked for me. I had a n option using alt+enter to import the top-level operator. Not sure why it would not work for you


#9

I’m not sure. Honestly, I need to double check since @Wasabi375 has it working. Are you trying to auto import from the same project as your common.number.Number.kt top-level function? Is it in the same module?

I remember there being a specific case where auto-import didn’t work for me–which did not include functions in the same project. This may explain why it auto import works for some top-level functions and not others.