Lingara Lingara 說明文件 學習指南 API 函式庫 應用程式 起造 網頁版
語言: 閩南語

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,所以對 in 做 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.

這頁包的內容