如何在Kotlin中声明具有两种类型的变量,如val x:Int或String

如何在Kotlin中声明具有两种类型的变量,如val x:Int或String

问题描述:

我要写一个像这样的方法:

I'm gonna write a method like:

object UIBehavior {
   fun dialog(context: Context, title: Int | String, message: Int | String){
     val dialogObj = AlertDialog.Builder(context)
     dialogObj.setTitle(title)
     dialogObj.setMessage(message)
   }
}

方法 dialogObj.setTitle dialogObj.setMessage 允许两种类型的参数,而我如何删除可以让方法 dialog 的参数em>只允许Int和String这两种类型吗?

The methods dialogObj.setTitle and dialogObj.setMessage allow two types of parameters, and how can I delare the parameter that can let the method dialog allow only two types Int and String?

您不能在Kotlin中做到这一点.

You can't do that in Kotlin.

但是您可以使用一个功能的多个版本,例如

But you can have multiple versions of a function, e.g.

object UIBehavior {
    fun dialog(context: Context, titleId: Int, messageId: Int){
        val titleString = context.getString(titleId)
        val messageString = context.getString(messageId)
        dialog(context, titleString, messageString)
    }

    fun dialog(context: Context, title: String, message: String) {
        val dialogObj = AlertDialog.Builder(context)
        dialogObj.setTitle(title)
        dialogObj.setMessage(message)
    }
}

这样,您可以简单地使用id或字符串来调用该函数,看起来您正在使用相同的函数

That way you can simply call the function with either ids or strings and it looks like you are using the same function

UIBehavior.dialog(this, R.string.title, R.string.message)
UIBehavior.dialog(this, "title", "message")

您还可以使用IntString的通用超类型,但这将允许更多的超类,我不建议这样做.

You could also use a common supertype of Int and String but that would allow a lot more and I wouldn't recommend that.

fun dialog(context: Context, title: Any, messageId: Any){
    val titleString = when (title) {
        is String -> title
        is Int -> context.getString(title)
        else -> throw IllegalArgumentException("Unsupported type")
    }
    val messageString = when ...
       ...
    dialog(context, titleString, messageString)
}

泛型在这里也不起作用,因为您不能动态调用dialogObj.setTitle(title).在编译时必须知道要调用该函数的Int还是String重载.与使用Any并没有什么不同.

Generics don't work here either because you can't call dialogObj.setTitle(title) dynamically. It must be known at compile time whether you want to call the Int or the String overload of that function. It's also not really different from using Any.