https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Jasin Colegrove

01/07/2022, 7:02 PM
I have this code
val pdfDoc = PdfDocument(PdfWriter(fileName))
but the implementation for PdfDocument is
Copy code
public PdfDocument(PdfWriter writer) {
        this(writer, new DocumentProperties());
    }
what is pdfDoc assigned to with no return value?
k

Kirill Grouchnikov

01/07/2022, 7:03 PM
This is a constructor
👆 1
r

Rodrigo Bressan De Souza

01/07/2022, 7:04 PM
I guess pdfDoc is the object of the class PdfDocument
👍 1
k

Kirill Grouchnikov

01/07/2022, 7:04 PM
Is this a Java code snippet, or a Kotlin code snippet?
a

Ayfri

01/07/2022, 7:18 PM
This looks like Java
👍 2
k

kqr

01/07/2022, 8:04 PM
I guess it is kotlin code using java lib 🙂
r

Rob Elliot

01/07/2022, 8:15 PM
Yup., I'd guess the Java looks like this:
Copy code
public class PdfDocument {

    public PdfDocument(PdfWriter writer, DocumentProperties documentProperties) {
    }

    public PdfDocument(PdfWriter writer) {
        this(writer, new DocumentProperties());
    }
}
The equivalent Kotlin would be:
Copy code
class PdfDocument(
  writer: PdfWriter, 
  properties: DocumentProperties = DocumentProperties(),
)
Or if you wanted it to be the basically the same byte code:
Copy code
class PdfDocument(
  writer: PdfWriter,
  properties: DocumentProperties,
) {
  constructor(writer: PdfWriter): this(writer, DocumentProperties())
}
k

Kirill Grouchnikov

01/07/2022, 8:23 PM
The way I read the question was that
public PdfDocument(PdfWriter writer)
doesn't seem to return anything - and that is true in the Kotlin world. But in the Java world that's the constructor syntax, so the "return" of that is a
PdfDocument
object
a

Ayfri

01/07/2022, 8:44 PM
Wait, if you put a default value for an argument in the constructor it won't generate the same bytecode as two constructors with the second one using the default value for the argument ?
e

ephemient

01/07/2022, 8:45 PM
not quite, no
a

Ayfri

01/07/2022, 8:47 PM
Why, and what would be the difference ?
e

ephemient

01/07/2022, 8:47 PM
without
@JvmOverloads
Kotlin generates a constructor taking every parameter, a bitmask of which parameters are present (or several, depending on how many arguments there are), and a DefaultConstructorMarker (for overload disambiguation)
a

Ayfri

01/07/2022, 8:48 PM
Oh yes I remember now that it's doing that
e

ephemient

01/07/2022, 8:48 PM
very much not something that is intended to be used from Java
a

Ayfri

01/07/2022, 8:48 PM
So by default it's not interoperable with Java
e

ephemient

01/07/2022, 8:49 PM
it's technically callable… but it involves too many low-level details that you shouldn't
9 Views