Search code examples
javamavenkotlinunexpected-token

How to use java library from kotlin program?


I am programming in Kotlin.

I need to use a library, which is written in java and comes from maven central.

I put the dependency in my pom.xml and can import the library in my Kotlin code.

However, I am not able to understand how I can use that java library from Kotlin.

From the tutorials, in Java, the library should be used as (it is used to generate PDF):

//Initialize writer
PdfWriter writer = new PdfWriter(dest);

//Initialize document
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);

//Add paragraph to the document
doc.add(new Paragraph("Hello World!"));

//Close document
doc.close();

But how should I do in Kotlin, I tried the following:

import com.itextpdf.kernel.pdf.PdfDocument
import com.itextpdf.kernel.pdf.PdfWriter

class PDFService {
    
    fun generateSimplePdf(value: String) {
        println("I am generating a PDF for $value :)")
        val writer: PdfWriter(dest)

        val document: PdfDocument(writer)
    }
}

But the arguments of PdfWriter and PdfDocument give: "Unexpected token".

How should I do that ? In a more general way, is there a reference on how to use java inside kotlin ? (This documentation is not very helpfull).


Solution

  • From Tenfour04 from the comments:

    This has nothing to do with using Java classes in Kotlin. Your Kotlin syntax is incorrect. Use val write = PdfWriter(dest). Note =, not :. Same with your document line. The colon is for specifying the type. An equal sign is for assigning a value. Type can usually be omitted because it can be inferred from what you initially assign.