2016-11-14 18 views
3

上の一般的な操作:Kotlin、数

interface fun_vector2_common { 

    fun abs(res: Vec2, a: Vec2): Vec2 { 
     res.x = glm.abs(a.x) 
     res.y = glm.abs(a.y) 
     return res 
    } 
} 

は、それが実現することが可能ですジェネリックを使ってabsとしましょうか?

interface fun_vector2_common<T : Number> { 

    fun abs(res: Vec2t<T>, a: Vec2t<T>): Vec2t<T> { 
     res.x = glm.abs(a.x) // error 
     res.y = glm.abs(a.y) // error 
     return res 
    } 
} 

これに対応するglm.abs()は、タイプに基づいて呼び出されますか?

それは期待するので、上記のコードは、明らかに、glm.abs(n: Number)

+0

可能な重複[Kotlin内のすべての数値タイプのフロアモジュロを実装する方法?](https://stackoverflow.com/questions/38052008/how-to-implement-floor-modulo-for-every-number-type-in​​-kotlin) – outis

+0

さまざまな解決策が提案されています。 Kotlinに追加される[構造型](https://youtrack.jetbrains.com/issue/KT-218)のリクエストがありますが、牽引力はないようです。かなり最近[タイプクラス](https://github.com/Kotlin/KEEP/pull/87)のKEEPが作成されました。基本的に型クラスであるが、拡張関数の拡張として発生する[拡張型](https://discuss.kotlinlang.org/t/extension-types-for-kotlin/1390/14)に関する広範な議論もある。 – outis

答えて

2

残念ながらthere's no clean way to have generic abs functionを失敗しました。

object glm { 
    fun <T : Number> abs(x: T): T { 
     val absoluteValue: Number = when (x) { 
      is Double -> Math.abs(x) 
      is Int -> Math.abs(x) 
      is Float -> Math.abs(x) 
      is BigDecimal -> x.abs() 
      is BigInteger -> x.abs() 
      else -> throw IllegalArgumentException("unsupported type ${x.javaClass}") 
     } 
     @Suppress("UNCHECKED_CAST") 
     return absoluteValue as T 
    } 
} 

あなたのコンテキストで使用することが可能になるだろう:あなたは、次のabsの定義とそれを回避することができます

fun abs(res: Vec2, a: Vec2): Vec2 { 
    res.x = glm.abs(a.x) 
    ... 
}