4

Let say we have a kotlin class defined as:

package foo

class Bar internal constructor() {
//...
}

When I try to init that object from a test method like:

package foo


class TestBar {
    @Test
    fun testingBar() {
        Bar()  //<----- error
    }
}

I get a following error:

Cannot access '<init>': it is internal in 'Bar'

Both Bar and TestBar are in the same AndroidStudio module (android library) Both paths to sources were defined in a gradle:

...
sourceSets {
    main.java.srcDirs += 'src/main/kotlin'
    test.java.srcDirs += 'src/test/kotlin'
}
...

Tests seem to work fine in general, but I'm unable to create any object with a internal constructor.

I'm using:

ext.kotlin_version = '1.1.3-2'

EDIT

Thanks for the feedback. I've decided to make simple android multi-module application from scratch and it worked just fine.

Then I tried to get rid of my module dependencies one by one and it turns out that problem is caused by dagger2 gradle dependency.

dependencies {
    ...

    //dagger 2
    implementation 'com.google.dagger:dagger:2.8'
    kapt 'com.google.dagger:dagger-compiler:2.8'
}

When I remove the dependency I am able to access internal constructor from tests without a problem. Is that an indication of a bug or my dependency is not defined properly?


EDIT 2 (Solution)

It turns out that problem was caused by kapt's generatestubs = true option. In order to make tests see internal classes just switch to a new kapt implementation:

http://kotlinlang.org/docs/reference/kapt.html

which in my case came down to getting rid of

kapt {
    generateStubs = true
}

and adding

apply plugin: kotlin-kapt'

at the beginning of gradle file.

Marcin
  • 893
  • 7
  • 19

1 Answers1

2

internal visibility means that the class is visible only in the same module. Kotlin's definition of a module is:

More specifically, a module is a set of Kotlin files compiled together:

  • an IntelliJ IDEA module;
  • a Maven project;
  • a Gradle source set;
  • a set of files compiled with one invocation of the Ant task.

As far as I know you main and test are 2 separate source sets and that's the reason why it's not working.

main.java.srcDirs += 'src/main/kotlin'
test.java.srcDirs += 'src/test/kotlin'
Mibac
  • 8,990
  • 5
  • 33
  • 57