Search code examples
kotlinintellij-idea

kotlin Importing sign and floordiv in intellij


This is probably a dumb question, but I'm struggling to use sign and floordiv, and I'm assuming its an importation issue.

I was trying to implement a function to get rounded up division. (I found the function on SE) One error says Kotlin: Unresolved reference: floorDiv and the otherKotlin: Type mismatch: inferred type is Int but Double was expected

I checked kotlinlang.org, floordiv seems to be in the standard library https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/floor-div.html

and for sign, kotlinlang says it works for Int val Int.sign: Int, as well as the error on play.kotlinlang.org

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public val Double.sign: Double defined in kotlin.math public val Float.sign: Float defined in kotlin.math public val Int.sign: Int defined in kotlin.math public val Long.sign: Int defined in kotlin.math

I imported sign with import kotlin.math.sign

I know I'm probably missing something dumb, but I can't figure it out, and I can't find anything online as to what the issue might be.

EDIT:

the code that is throwing the error is

var result = dividend / divisor + sign(dividend % divisor)

or

fun Int.ceilDiv(other: Int): Int { return this.floorDiv(other) + this.rem(other).sign.absoluteValue }

I tried bringing it out of the function to try and debug, also changed it a bit so I could read it clearer. Both throw errors.

EDIT2: If the above code snippets don't count as Minimum Reproducable Example, I copied this from where I tried in KotlinLang:

import kotlin.math.sign

fun main() {
    for(dividend in 1..10){
        for(divisor in 1..5){
            var rem = dividend % divisor
            var result = dividend / divisor + sign(rem)
            print(result)
        }
    }
}

I've tried both sign(rem) and Int.sign(rem), the error is Type mismatch: inferred type is Int but Double was expected


Solution

  • Functions and properties that are declared like these:

    fun Int.floorDiv(other: Int)
    val Int.sign: Int
    

    where there is a type name and a dot before the name of the function/property, are extensions.

    Instead of calling them like this:

    floorDiv(a, b)
    sign(x)
    

    You should use them like this:

    a.floorDiv(b)
    x.sign