Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

private visibility modifier and subpackages

Tags:

kotlin

So I recently started experimenting with Kotlin and I stumbled upon this:

If a top-level declaration is marked private, it is private to the package it’s declared in (see Visibility Modifiers). Since packages really nest in Kotlin, i.e. package foo.bar is considered a member of foo, if something is private in a package, it is visible to all its subpackages.

Note that members of outer packages are not imported by default, i.e. in a file in package foo.bar we can’t access members of foo without importing them. From: Visibility and Package Nesting

So let's consider the following example:

File1.kt

package foo

private fun bar() = println("This is bar!!!")

and File2.kt

package foo.baz

import foo.bar

fun main(args: Array<String>) = bar()

From what I understand function bar() should be visible in package foo.baz and thus be callable from main(). But when I try to compile the above I get the following error message:

Error: Kotlin: Cannot access 'bar': it is 'private' in 'foo'

Is this a bug or has the spec of the language been updated and the documentation hasn't? Am I missing something?

Thanks in advance.

like image 420
feugatos Avatar asked Jul 22 '15 17:07

feugatos


1 Answers

We have changed the visibility rules recently, so that packages do not nest any more. So this is not a bug in the compiler, but in the docs

like image 182
Andrey Breslav Avatar answered Jan 03 '23 22:01

Andrey Breslav