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

Susmitha Gudapati

05/30/2022, 1:16 PM
Hi, I have a typescript application. I want to create a Kotlin based application basing the same ts contracts/states. So I’ve started converting them from typescript to kotlin using custom scripts. While doing so, I’m facing a few challenges and one of them is to identity the kotlin’s equivalent implementation of typescript’s optional property, which is denoted by
?
in states. For example: My contract in ts is -
Copy code
export interface A {
    id: number,
    name: string,
    imageId?: number,
    modified?: string,
}
In the interface A, the imageId and modified properties are optional. How do we denote the same functionality in kotlin’s classes?
s

Susmitha Gudapati

05/30/2022, 1:50 PM
But this is defining that a property can be a null. So in short, nullable type. I'm looking for optional properties in an object
r

Roukanken

05/30/2022, 1:58 PM
Sadly (thankfully?) Kotlin has no such thing as optional properties. You can emulate the functionality with one of (or multiple of): a) nullable types b) default arguments c) class inheritance based on what exactly your classes represent
and @nullable types:
property?: type
in interface is same as if you said
property: type | undefined
so if you had a Kotlin
Copy code
data class A(
    id: Int,
    name: String,
    imageId: Int? = null,
    modified: String? = null,
)
then it's constructor would behave same as constructing ts/js objects in interface A eg, equivalent of
Copy code
const a: A = {
    id: 1,
    name: "The Answer",
    imageId: 42,
}
would be
Copy code
val a = A(
    id = 4,
    name = "The Answer",
    imageId = 42,
)
(and yes,
modified
would be
null
and not
undefined
, but unless you do some heavy magic, you won't be able to distinguish the two... but your TS code also shouldn't make difference between null & undefined)
s

Susmitha Gudapati

05/30/2022, 2:25 PM
okay cool, thanks.
5 Views