Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate UUID on kotlin-multiplatform?

Are there any kotlin-multiplatform common functions to get a UUID/GUID?

 // ideally something like this
 val newUUID = UUID() // "1598044e-5259-11e9-8647-d663bd873d93"
 println("newUUID = $newUUID")

I'd prefer not to make separate Android and iOS versions using expect-actual.

like image 923
Veener Avatar asked Mar 29 '19 19:03

Veener


People also ask

What is kotlin UUID?

kotlin.Any. ↳ java.util.UUID. A class that represents an immutable universally unique identifier (UUID). A UUID represents a 128-bit value.18-Feb-2021.

How do you generate a UUID from a string?

The fromString() method of UUID class in Java is used for the creation of UUID from the standard string representation of the same. Parameters: The method takes one parameter UUID_name which is the string representation of the UUID. Return Value: The method returns the actual UUID created from the specified string.

What is UUID randomUUID ()?

The randomUUID() method is used to retrieve a type 4 (pseudo randomly generated) UUID. The UUID is generated using a cryptographically strong pseudo random number generator.


2 Answers

That one may work https://github.com/benasher44/uuid

The sources of the project use the Kotlin Multiplatform project to implement the UUID library. See https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html for more details

like image 74
Eugene Petrenko Avatar answered Oct 22 '22 00:10

Eugene Petrenko


As per the Kotlin multiplatform documentation, you can make an expect/actual function to use the Android (java) and iOS (NSUUID) specific implementations:

// Common
expect fun randomUUID(): String
// Android
import java.util.*

actual fun randomUUID() = UUID.randomUUID().toString()
// iOS
import platform.Foundation.NSUUID

actual fun randomUUID(): String = NSUUID().UUIDString()
like image 3
Schadenfreude Avatar answered Oct 22 '22 01:10

Schadenfreude