Lingara Lingara 說明文件 學習指南 API 函式庫 App 建立 網頁版
語言: 客家話

Kotlin

這頁係對英文翻譯過來个。若係兩片無共樣,以英文頁為準。 看英文頁

Kotlin 函式庫係 Maven Central 頂高个 com.getlingara:lingara-kotlin。佢在 JVM 頂高行,愛 Java 17 摎 Kotlin 2.2 抑係較新个版本,也用 kotlinx.coroutines 摎 kotlinx.serialization。

用起來仰般

  • 每隻呼叫都係 suspend 函式。取消該隻協程就做得取消呼叫,抑係用 withTimeout 設一隻截止時間;你看著个係你自家个 CancellationException,從來毋會係包過一層个。
  • 串流係一隻 EventStream,就係一隻淨收集一擺个 Flow。在 use 肚收集佢,恁樣用了佢就會自家關忒。事件係密封介面下背个資料類別,用 when 來對。
  • 錯誤繼承自密封類別 LingaraException,所以對佢兜做 when 係窮盡个。retryAfter 係一隻 Duration,若係 API 無講愛等幾久就係 null。
  • 用 LingaraClient { } 建構器來建立用戶端。佢用 JDK 个 HttpClient,你做得換做你自家个。

下背个範例會加入相依套件、建立用戶端、用串流拿一份詞彙清單,還有處理錯誤。

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.

這頁包裝个內容