English 中文(简体)
在确定参数对未指明的参数价值时,是否可以称之为具有任择参数的建筑商?
原标题:Is there a way to call a constructor with optional parameters, while setting the parameter value to unspecified ?
  • 时间:2024-01-13 05:20:00
  •  标签:
  • kotlin

If I have methods below:

fun testMethod(
  test1: Int = 5,
  test2: String = "hello",
  test3: Boolean = true,
) {
  // do some stuff
}
fun callerMethod(
  caller1: Int,
  caller2: String,
  caller3: Boolean,
) {
  // do some stuff
  testMethod(test1 = caller1, test2 = caller2, test3 = caller3)
}

是否有办法修改上述电线,以便其参数探测器1、电线2、电线3是任择性的,如果未提供,则测试。 如何使用为测试1、测试2和测试3设定的缺省值?

我不想这样做,因为对违约价值有两种真相来源:

fun callerMethod(
  caller1: Int = 5,
  caller2: String = "hello",
  caller3: Boolean = true,
) {
  // do some stuff
  testMethod(test1 = caller1, test2 = caller2, test3 = caller3)
}

我希望我能做如下一些事情,但没有得到支持。

fun callerMethod(
    caller1: Int? = null,
    caller2: String? = null,
    caller3: Boolean? = null
) {
    // do some stuff
    testMethod(
        test1 = caller1 ?: Unspecified,
        test2 = caller2 ?: Unspecified,
        test3 = caller3 ?: Unspecified
    )
}

而且,由于测试方法属于第3个政党图书馆,我无法加以修改,因此,我可以产生全球变量,设定默认值。

为了提供某种背景,Im公司目前学习Atpe Compose,其基建构件平均有10个参数,具有大量违约值。 我正在创建我自己的倡议组成部分,呼吁它们,并处理这一问题。

问题回答

You can do it with reflection, for example:

fun callerMethod(
    caller1: Int? = null,
    caller2: String? = null,
    caller3: Boolean? = null,
) {
    val testMethodRef = ::testMethod
    val testParams = testMethodRef.parameters
    // testParams is a List of parameters of testMethod
    // testParams[0] is test1 and so on
    val testArgs = buildMap {
        if (caller1 != null) { put(testParams[0], caller1) }
        if (caller2 != null) { put(testParams[1], caller2) }
        if (caller3 != null) { put(testParams[2], caller3) }
    }
    // Now we create a Map of parameters that we want to change to arguments
    testMethodRef.callBy(testArgs)
    // And call testMethod with those arguments only
}

您可能不得不在<代码>build.gradle.kts上添加一个附属关系:

dependencies {
    implementation(kotlin("reflect"))
}




相关问题
Exposed runs query on all HikariCP open connections

I m running a Ktor server with a PostgreSQL database and just set up the JetBrains Exposed ORM framework with HikariCP for connection pooling (per the recommendation in the Ktor documentation). My ...

SQLite Kotlin issue - no database

I am trying to create boardgamegeek APIs based app in AndroidStudio, however from unknown reason I m getting my database created with no columns. Here s Logical log: (1) no such table: games in "...

Flutter App cannot be installed on Android TV

I m building a Flutter app that should support Android TV and Mobile devices. Despite Google Play shows that it is supported, I cannot install app on my MiBox device. While trying to install it, both ...

热门标签