David Lee
03/13/2023, 11:45 PMval sides = arrayOf<Number>(1,2,3)
val sum = sides[0] + sides[1]
// Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: [...much detail]
ephemient
03/13/2023, 11:48 PMNumber
, only on concrete subtypesBlake MacDade
03/13/2023, 11:51 PMephemient
03/13/2023, 11:52 PMintArrayOf(1, 2, 3)
will result in a primitive IntArray
David Lee
03/13/2023, 11:54 PMDavid Lee
03/13/2023, 11:58 PMTriangle<out T : Number>(val a: T, val b: T, val c: T)
and I need to find a way to coax T into something concrete I can add up …
helicopter dogging:
val sides = arrayOf(a,b,c) as Array<Double>
David Lee
03/14/2023, 12:00 AMval da: Double = a as Double
val db: Double = b as Double
val dc: Double = c as Double
val sides = arrayOf<Double>(da,db,dc)
seems to compile but isn’t very succinct …ephemient
03/14/2023, 12:02 AMarrayOf(a, b, c).sumOf { it as Double }
will sum them as doubles, but if you know it's double, you should at least have a Triangle<Double>
David Lee
03/14/2023, 12:02 AMval sides = arrayOf<Double>(a as Double,b as Double,c as Double)
slight improvement 🤷Blake MacDade
03/14/2023, 12:04 AMval sides = arrayOf(a, b, c).map { it as Double }
Joffrey
03/14/2023, 12:21 AMTriangle<Double>
as input, you shouldn't need to cast. If you don't know (e.g. you get Triangle<*>
), you shouldn't assume that you can cast to Double
. In that case, you should use .toDouble()
instead of as Double
so you guarantee you're actually converting to a double in all casesephemient
03/15/2023, 2:49 AMas Double
will throw if it's any other type of `Number`; .toDouble()
won't throw, but may lose information (9007199254740993L.toDouble() == 9007199254740992.0
, 1.toBigDecimal().shiftLeft(1024).toDouble() == Double.POSITIVE_INFINITY
, etc.)ephemient
03/15/2023, 2:52 AMNumber
is an open hierarchy so other types can be implemented, such as https://javadoc.io/doc/org.apache.commons/commons-numbers-complex/latest/index.html