Published by

Il y a 3 ans -

Temps de lecture 4 minutes

Platform-Specific implementations in Kotlin Multiplatform

Photo by Devon Rogers on Unsplash

In our last article, we covered how to structure your Kotlin project in order to support the Multiplatform features. However, in order to share portions of code between platforms and to define platform-specific implementations, we need to leverage some additional configurations and some interesting language features which we’re going to show in this post.

Defining a Platform-Specific implementation

package com.simonecivetta.services

class CircleService {
  fun circumferenceFor(radius: Double) = 2 * kotlin.math.PI * radius
    .also { /* How can we log? `print()` would work, but have we got anything better? */ } 
}

Interfaces

interface LoggerService {
  fun log(message: String-
}
package com.simonecivetta.services

class CircleService(val loggerService: LoggerService) {
  fun circumferenceFor(radius: Double) = 2 * kotlin.math.PI * radius
    .also { loggerService.log("circumferenceFor($radius): $it") }
}
// From Swift...
class SwiftLogger: NSObject, LoggerService {
  func log(message: String) {
    NSLog(message)
  }
}
// From Swift...
let logger = SwiftLogger()
let service = CircleService(loggerService: logger)
service.circumferenceFor(radius: 10.0)

Expect/Actual Mechanism

expect class LoggerService {
  fun log(message: String)
}
import platform.Foundation.NSLog
actual class LoggerService {
  actual fun log(message: String) {
    NSLog(message)
  }
}

Alright, which one should I choose?

Compile Time Checks

Language Interoperability

All that glitters…

Conclusion

Published by

Publié par Simone Civetta

Simone est responsable technique des équipes mobilités chez Publicis Sapient Engineering.

Commentaire

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Nous recrutons

Être un Sapient, c'est faire partie d'un groupe de passionnés ; C'est l'opportunité de travailler et de partager avec des pairs parmi les plus talentueux.