Home > Enterprise >  Pass value as reference in Kotlin
Pass value as reference in Kotlin

Time:03-30

I want to convert code Objective C to Kotlin multiplatform This is Objective C code

{
    NSFileManager *fileManager = [[NSFileManager alloc] init];

    BOOL isDir;
    BOOL exists = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    BOOL success = false;

    if (isDir && exists) {
        NSURL *pathUrl = [NSURL fileURLWithPath:path];
        NSError *error = nil;
        success = [pathUrl setResourceValue:isExcluded
                                     forKey:NSURLIsExcludedFromBackupKey
                                      error:&error];

        if (!success) {
            NSLog(@"Could not exclude AsyncStorage dir from backup %@", error);
        }
    }
    return success;
}

In above code variable isDir use & when pass to function fileExistsAtPath So how can I use isDir like that in Kotlin. I know this is address-of unary operator

Can I use

  val isDir: CPointer<BooleanVar /* = kotlinx.cinterop.BooleanVarOf<kotlin.Boolean> */>? = null
        val exists = fileManager?.fileExistsAtPath(path, isDir)

CodePudding user response:

To create a pointer in Kotlin, you need memScoped, inside this scope you can call alloc to create a pointer of any type.

Here's how you code can be written in Kotlin:

return memScoped {
    val fileManager = NSFileManager.defaultManager
    val isDir = alloc<BooleanVar>()
    val exists = fileManager.fileExistsAtPath(path, isDirectory = isDir.ptr)
    var success = false
    if (exists && isDir.value) {
        val pathUrl = NSURL.fileURLWithPath(path)
        val error = alloc<ObjCObjectVar<NSError?>>()
        success = pathUrl.setResourceValue(isExcluded, forKey = NSURLIsExcludedFromBackupKey, error = error.ptr)
        if (!success) {
            println("Could not exclude AsyncStorage dir from backup ${error.value}")
        }
    }
    return@memScoped success
}

CodePudding user response:

You can pass lambda and change bool value in it

var isDir: Boolean = false
fileExistsAtPath(onChange = { newValue -> isDir = newValue })

but I think this is NOT a good approach. Try to create data class with 2 fields: isDir and exists, or use Pair at least. And return them from function fileExistsAtPath

  • Related