Skip to content

Commit 604c539

Browse files
committed
feat(bsonkt): more ID util functions
- added BsonElement.toIDOrNull()
1 parent c12fb37 commit 604c539

1 file changed

Lines changed: 28 additions & 3 deletions

File tree

  • module-bsonkt/src/commonMain/kotlin

module-bsonkt/src/commonMain/kotlin/ID.kt

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,8 @@ fun AnyID.toObjectIdOrNull(): ObjectId? {
104104
return null
105105
}
106106

107+
//
108+
107109
/**
108110
* Return an [ID] instance from the value of this.
109111
*/
@@ -114,11 +116,13 @@ inline fun <T> String.toID(): ID<T> {
114116
/**
115117
* Return an [AnyId] instance from the value of this.
116118
*/
117-
@JvmName("toAnyId")
119+
@JvmName("toAnyID")
118120
inline fun String.toID(): AnyID {
119121
return AnyID(this)
120122
}
121123

124+
//
125+
122126
/**
123127
* Return an [ID] instance from the value of this.
124128
*/
@@ -129,11 +133,13 @@ inline fun <T> ObjectId.toID(): ID<T> {
129133
/**
130134
* Return an [AnyId] instance from the value of this.
131135
*/
132-
@JvmName("toAnyId")
136+
@JvmName("toAnyID")
133137
inline fun ObjectId.toID(): AnyID {
134138
return AnyID(this)
135139
}
136140

141+
//
142+
137143
/**
138144
* Cast this [ID] to an id of [T].
139145
*/
@@ -144,11 +150,30 @@ inline fun <T> AnyID.toID(): ID<T> {
144150
/**
145151
* Cast this [ID] to [AnyId].
146152
*/
147-
@JvmName("toAnyId")
153+
@JvmName("toAnyID")
148154
inline fun AnyID.toID(): AnyID {
149155
return AnyID(this)
150156
}
151157

158+
//
159+
160+
fun <T> BsonElement.toIDOrNull(): ID<T>? {
161+
return when (this) {
162+
is BsonString -> ID(this.value)
163+
is BsonObjectId -> ID(this.value)
164+
else -> null
165+
}
166+
}
167+
168+
@JvmName("toAnyIDOrNull")
169+
fun BsonElement.toIDOrNull(): AnyID? {
170+
return when (this) {
171+
is BsonString -> AnyID(this.value)
172+
is BsonObjectId -> AnyID(this.value)
173+
else -> null
174+
}
175+
}
176+
152177
/* ============= ------------------ ============= */
153178

154179
/**

0 commit comments

Comments
 (0)