Simple Generic Function in Kotlin Fails

后端 未结 1 1152
小鲜肉
小鲜肉 2021-01-25 14:31

Here\'s a simple generic function in Kotlin:

fun  twice(x: T) : T { return 2 * x }

Attempting to build this (either in a project or RE

1条回答
  •  礼貌的吻别
    2021-01-25 15:16

    Since T could be anything, the compiler is not able to find a matching times operator. As you can see in the error message, for Int, there a multiple alternatives available

    public final operator fun times(other: Byte): Int defined in kotlin.Int
    public final operator fun times(other: Double): Double defined in kotlin.Int
    public final operator fun times(other: Float): Float defined in kotlin.Int
    public final operator fun times(other: Int): Int defined in kotlin.Int
    public final operator fun times(other: Long): Long defined in kotlin.Int
    public final operator fun times(other: Short): Int defined in kotlin.Int
    

    But unfortunately there's no generic times function, which can be used with e.g. Number. I'm afraid in this case, you would have to create an overload for each type you want to be handling, i.e., Double, Int, etc.

    0 讨论(0)
提交回复
热议问题