簡體   English   中英

如何在Kotlin中聲明一個可以是字符串或函數的函數參數?

[英]How can I declare a function parameter that can be a string or a function, in Kotlin?

在下面的函數中,我想傳遞一個html標記的屬性。 這些屬性可以是字符串( test("id", "123") )或函數( test("onclick", {_ -> window.alert("Hi!")}) ):

fun test(attr:String, value:dynamic):Unit {...}

我試圖將參數value聲明為Any ,即Kotlin中的根類型。 但是函數不是Any類型。 將類型聲明為dynamic工作,但是

  • dynamic不是一種類型。 它只是關閉鍵入檢查參數。
  • dynamic僅適用於kotlin-js(Javascript)。

如何在Kotlin(Java)中編寫此函數? 函數類型如何與Any相關? 是否有包含函數類型和Any類型?

你可以重載函數:

fun test(attr: String, value: String) = test(attr, { value })

fun test(attr: String, createValue: () -> String): Unit {
    // do stuff
}

你可以寫:

fun test(attr: String, string: String? = null, lambda: (() -> Unit)? = null) {
  if(string != null) { // do stuff with string }
  if(lambda != null) { // do stuff with lambda }
  // ...
}

然后通過以下方式調用該函數:

test("attr")
test("attr", "hello")
test("attr", lambda = { println("hello") })
test("attr") { println("hello") }
test("attr", "hello", { println("hello") })
test("attr", "hello") { println("hello") }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM