ChatGPT解决这个技术问题 Extra ChatGPT

Package protected alternative in Kotlin

In Java, we have the package protected (default) modifier for classes, which allows us to have many classes in a single package but exposes only a few and keeps the logic encapsulated.

With Kotlin this doesn't seem to be the case. If I want a few classes to be visible to each other but no further, I have to use a private modifier which limits visibility to a single file.

So if you want 10 classes in a package but only one of them to be public, you'd have to have one huge file with all the classes in it (and private all over the place).

Is this normal practice or there is a way to achieve some similar modularity in Kotlin?

I don't understand: if they have the notion of a package, why did they get rid of package protected access?

Update: We might have package protected visibility after all
see the discussion here

Update: If you read through the discussion and still think this is a must-have feature for the language, please vote here

More discussion linked: discuss.kotlinlang.org/t/…
There is a feature request for package-private visibility or an equivalent: KT-29227.
Kotlin offers internal
internal is very different thing, if i were to use internal to replace package visibillity id have 200 modules
what he mean is internal is module private not package private

h
hotkey

Kotlin, compared to Java, seems to rely on packages model to a lesser degree (e.g. directories structure is not bound to packages). Instead, Kotlin offers internal visibility, which is designed for modular project architecture. Using it, you can encapsulate a part of your code inside a separate module.

So, on top level declarations you can use

private to restrict visibility to the file

internal to restrict visibility to the module

At this point, there is no other option for visibility restriction.


Well i like the internal, but we will have that fixed much better in java9 however i never ever saw that someone would create the same package just to use code... after all if someone is that much determined to violate the modularity he will just copy paste the code if necessary... What i'm concerned here is usability. cos simply putting ton of code in one file is dumb...
Ok but right now i'm migrating a java project to kotlin, and i have very good visibility enforced, tipicaly these are some utilities that are composed of 4-5 classes only one of which is visible to the outside world... Now with kotlin i have no option to have the same visibility unless i put everything in the same file... Do i understand it correctly or there is some other approach i dont know of?
@JaysonMinard I agree about small classes. But let's say your Java package consists of 5 classes, 200 lines each, and suddenly to mimic the same visibility in Kotlin you have to create a 1000 lines long file. That's what I was calling controversial above.
Package level visibility is just cool in Java. Even it can be "hacked" you don't have to do it. It makes unit testing of protected stuff easy and well separated. "protected" visibility in Java also increases readability, it says you mustn't use the member directly, unless you are the package maintainer. Breaking down a project into more projects/modules just for the right visibility issues just doesn't make sense, just annoying extra work. So in this issue Java is still better than Kotlin.
"the main flaw of Java's package protected visibility is that everyone can still access your code" - a rather poor reason if you ask me. You can use reflection to access anything you want anyway. Access modifiers are not for security, they are for preventing accidental mistakes and specifying API contracts. If someone writes the code inside the same package, it's safe to assume that this isn't an accident and he must know what he is doing. If you want security, use SecurityManager.
e
esentsov

As a workaround for me on android I've created @PackagePrivate annotation and lint checks to control access. Here you can find the project.

Lint checks are obviously not that strict as compiler checks and some setup needed to fail the build on errors. But android studio picks up lint checks automatically and shows error immediately while typing. Unfortunately I don't know a way to exclude annotated members from autocomplete.

Also, as lint is a purely compile-time tool, no checks at runtime performed.


is it actually specific for android? kotlin is not just android it would be awesome to have libs generic when possible
Unfortunately it's android specific and the reason is is uses Android Lint. Android Studio supports it nicely and runs the checks on the fly, showing errors in the IDE itself immediately. It's probably possible to implement these checks with something like ktlint, but without IDE support user experience is really bad for such kind of checks.
Hint: You can make it more like a keyword and avoid having to import it on every file by adding type aliases on each package, for example: internal typealias pkg = io.github.esentsov.PackagePrivate; internal typealias private = io.github.esentsov.FilePrivate. And use it like @pkg val ... @private internal val ...
U should look into the @hide annotation of android for excluding in autocomplete.
I'd gladly include something like this in my project even without IDE support. Are you aware of a way to do this? I use IDEA, which is a superset of Android studio. It's strange why you need to include android packages :(
D
DPM

As @hotkeys points out, you can use the internal keyword in a module or you can put all classes that would otherwise belong in a package inside a single file, but sticking several classes in a file may be a questionable design decision.

For me, the package visibility is helpful for its documenting value. I want to know what public interface some package is presenting to the rest of the project, hide factory implementation classes and so on.

So even if it's possible to access package-private classes and methods in Java, I still choose to use the package modifier.

For this I created a project with a single annotation:

package com.mycompany.libraries.kotlinannotations;

import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.SOURCE;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Documented
@Retention(SOURCE)
@Target({ TYPE, METHOD, CONSTRUCTOR })
/**
 * Use in Kotlin code for documentation purposes. 
 * 
 * Whenever a Kotlin class or method is intended to be accesible at package level only.
 *
 */
public @interface PackagePrivate {

}

Then I can use this annotation in any Kotlin project.

The second step, which I haven't done yet, is creating a PMD rule to enforce this with maven (or any other build tool for that matter) and also be able to see violations of the rule in my IDE with the pmd plugin.

There no is full Kotlin support in pmd at this moment but it seems to be expected at some point.


A
Agent_L

Package-based protection is pointless in Kotlin because packages themselves are unprotected

In Java, package was tied to directory structure. So if you put your classes in com\example\yoursecretengine, any attempt (deliberate or accidental) to add a rogue class there would be easily noticeable. This is the kind of security we've depended on.

Kotlin removes the ties between directory and package, so I can put my class in "my" directory (eg.src\java\pl\agent_l\illegalaccess) yet declare its package as com.example.yoursecretengine - and gain access to all the properties you've meant as package private.

In fact, a Kotlin project works perfectly without ANY package declarations. This only highlights that packages are "more what you'd call guidelines than actual rules". They're a convenience feature, useful only to unclutter namespace and nothing more.

Relevant quotes from kotlinlang:

unlike many other languages, Kotlin packages do not require files to have any specific locations w.r.t. itself; the connection between a file and its package is established only via a package header.

And:

an absence of a package header in a file means it belongs to the special root package.


please see this
no one uses package visibility for any sort of security im tired of this argument, its about packaging your code in a nice way, it sucks putting related stuff in one file, as much as kotlin is compact it sucks to do that its that simple
they force you either put everything in one file or pollute public namespace if you are working on any non hello world project i bet you do one or the other
@vach This argument is getting repeated because people keep repeating this error. Both Java and Kotlin are general-purpose languages, so if general populace misuses a feature - that feature has negative value overall. Kotlin forces us into modules which is IMHO a good direction even if it feels like using sledgehammer to crack a nut at first. Package private is a horrible hack that makes you feel your code is neat when it's not. So you either embrace spaghetti or actually partition it with modules.
doesn't matter, i have debated about this so much i'm tired of it, i have no idea how people used it, to me package visibility was a way to separate components into multiple classes and only have one of them exposed, because its not in kotlin i see everyone doing huge files in kotlin like its some javascript, it sucks but i found my ways around it

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now