Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

gradle - Kotlin - Import Jar and Use Class

I have created a library in kotlin using gradle init and following the prompts. It compiles and produces a jar file in lib/build/libs. I then have another project that needs to access functions in the library. through intelliJ, I add the dependency by going to Project Settings > Modules > Dependencies and adding the jar file. I then attempt to import the package defined in the library with import DemoLib where DemoLib is the name of the package (and the name of the library). This does not compile as it does not recognize the package name. I have also tried importing as a library rather than a jar, with the same results. How can I achieve the desired result?

EDIT: In case it helps here is the code:

Library:

package DemoLib

class Library {
    fun someLibraryMethod(): Boolean {
        return true
    }
}

Client Code:

package DemoClientAppOne

import DemoLib.*



class App {
    val greeting: String
        get() {
            return "Hello World!"
        }
}

fun main() {
    println(App().greeting)
}

Not terribly interesting, but the point is that DemoLib is an unresolved reference even after adding the jar as a dependency

question from:https://stackoverflow.com/questions/65928854/kotlin-import-jar-and-use-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If DemoLib is a package,

you need to

import DemoLib.*

to import all its names into scope. Just import DemoLib wouldn't do anything. Or better,

import DemoLib.SomeClass

to import only one specific name. Actually, if you start typing SomeClass (assuming that's a name in your DemoLib package), IDEA should suggest adding the import.

Also, it's better to follow naming conventions from the beginning, and DemoLib is not a good package name:

Names of packages are always lower case and do not use underscores (org.example.project). Using multi-word names is generally discouraged, but if you do need to use multiple words, you can either simply concatenate them together or use camel case (org.example.myProject).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...