https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
a

Azur Haljeta

11/15/2020, 4:19 PM
In the spirit of practicing expect/actual constructs, I need a code which validates an email for iOS targets, but this turned to be harder than I thought 👇
This is how you would do it in Swift, as per StackOverflow:
Copy code
func isValidEmail(_ email: String) -> Bool {
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"

    let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    return emailPred.evaluate(with: email)
}
However, the
NSPredicate
constructor has different signature when used in
iosMain
. Is this even a constructor in Swift?
A Objective-C code from StackOverflow works better:
Copy code
- (BOOL)validateEmailWithString:(NSString*)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 
    return [emailTest evaluateWithObject:email];
}
but somehow won't compile when I rewrite this in Kotlin:
Copy code
fun emailValidation(email:String): Boolean {
    val emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
    val predicate = NSPredicate.predicateWithFormat("SELF MATCHES %@", emailRegex)
    return predicate.evaluateWithObject(email)
}
It fails with this error:
Copy code
Passing String as variadic Objective-C argument is ambiguous; cast it to NSString or pass with '.cstr' as C string
I don't want to use any 3rd party libraries for this. I'm learning KMM and want to do this on my own, especially because nobody should really use 3rd parties for such a simple task as email validation essentially is, but not in KMM?
And from your experience, how much proficiency is needed in Swift or even Obj-C to get the most out of KMM? I'm coming from a Android/Java/Kotlin background
c

corneil

11/15/2020, 4:26 PM
I would submit that using Kotlin Native to access a specific Native target you need a fair amount of proficiency in the target platform.
👍 2
a

Azur Haljeta

11/15/2020, 4:29 PM
there is a github issue for this problem https://github.com/JetBrains/kotlin-native/issues/1834 if I cast every string to
NSString
, it works Seems hacky to me but nevermind
g

gildor

11/15/2020, 11:46 PM
Kotlin/Native has own regular expressions, I would say that it would be better just use them, it would be also multiplatform
👍 1