Kotlin
ទំព័រនេះត្រូវបានបកប្រែពីភាសាអង់គ្លេស។ ប្រសិនបើទាំងពីរខុសគ្នា ទំព័រភាសាអង់គ្លេសគឺត្រឹមត្រូវ។ អានទំព័រភាសាអង់គ្លេស
បណ្ណាល័យ Kotlin គឺ com.getlingara:lingara-kotlin នៅលើ Maven Central។ វាដំណើរការនៅលើ JVM ត្រូវការ Java 17 និង Kotlin 2.2 ឬថ្មីជាងនេះ ហើយប្រើ kotlinx.coroutines និង kotlinx.serialization។
របៀបប្រើវា
- ការហៅនីមួយៗគឺជាមុខងារ
suspend។ បោះបង់ coroutine ដើម្បីបោះបង់ការហៅ ឬប្រើwithTimeoutសម្រាប់ពេលកំណត់ អ្នកឃើញCancellationExceptionផ្ទាល់ខ្លួនរបស់អ្នក មិនដែលឃើញមួយដែលត្រូវបានរុំទេ។ - ស្ទ្រីមគឺជា
EventStreamដែលជាFlowមួយដែលអ្នកប្រមូលតែម្តង។ ប្រមូលវានៅក្នុងuseដើម្បីឱ្យវាបិទនៅពេលអ្នករួចរាល់។ ព្រឹត្តិការណ៍គឺជា data class នៅក្រោម sealed interface ដែលផ្គូផ្គងដោយwhen។ - កំហុសពង្រីកពី sealed class
LingaraExceptionដូច្នេះwhenលើពួកវាគ្របដណ្តប់គ្រប់ករណី។retryAfterគឺជាDurationឬnullនៅពេល API មិនបានប្រាប់ពេលរង់ចាំ។ - បង្កើតក្លាយអិនដោយ builder
LingaraClient { }។ វាប្រើHttpClientរបស់ JDK ដែលអ្នកអាចជំនួសដោយរបស់អ្នកផ្ទាល់។
គំរូខាងក្រោមបន្ថែមការពឹងផ្អែក បង្កើតក្លាយអិន ស្ទ្រីមបញ្ជីវាក្យសព្ទ និងដោះស្រាយកំហុសមួយ។
Kotlin
implementation("com.getlingara:lingara-kotlin:0.1.0-alpha.6")Kotlin
import com.getlingara.kotlin.LingaraClient
val client =
LingaraClient {
clientCredentials(System.getenv("LINGARA_CLIENT_ID"), System.getenv("LINGARA_CLIENT_SECRET"))
}Kotlin
import com.getlingara.kotlin.LingaraClient
import com.getlingara.kotlin.model.GenerateVocabularyEvent
import com.getlingara.kotlin.model.VocabRequest
val request = VocabRequest(level = 2, sourceLang = "en", targetLang = "zh", count = 8)
// The request is sent here; collect the stream once, inside use {}.
client.generateVocabulary(request).use { stream ->
stream.collect { event ->
when (event) {
is GenerateVocabularyEvent.Item -> println("${event.data.word} ${event.data.translation}")
is GenerateVocabularyEvent.Started -> Unit
}
}
}Kotlin
try {
client.getUsage()
} catch (e: LingaraException) {
when (e) {
// A refusal from the API: status, code (stable) and message (localised).
is ApiException -> println("${e.status} ${e.code} ${e.message}; retry after ${e.retryAfter}")
// The token endpoint refused the credentials or the scopes.
is OAuthException -> println("${e.status} ${e.error} ${e.description}")
is MaintenanceException -> println("under maintenance; retry after ${e.retryAfter}")
// No usable answer: CONNECT, TLS, RESET, TIMEOUT, and so on.
is TransportException -> println("transport: ${e.kind}")
}
}
// A cancelled call throws the caller's own CancellationException instead.