Good point. So I just have to list all the array ...
# getting-started
n
Good point. So I just have to list all the array variants that Kotlin supports. Would be a nice candidate for the stdlib... Thanks for your help!
m
nkiesel: Don't forget that array can contain an array and
Arrays.toString(arrayOf(intArrayOf(0)))
will look ugly...
o
thanks, @miha-x64, it should be indeed recursive
Copy code
fun pretty(a: Any) : String = when (a) {
    is IntArray -> a.joinToString { pretty(it) }
    is DoubleArray -> a.joinToString { pretty(it) }
    else -> a.toString()
}
n
Yes, it's not that simple. Is it ever... I'll try to come up with something "reasonable" for nested arrays.
o
@nkiesel see above
n
yeah. Nice.
Latest (last?) iteration: using
Any?
, adding
[]
and enumerating all types from stdlib
Copy code
fun pretty(a: Any?): String = when (a) {
	is Array<*> -> a.joinToString(prefix = "[", postfix = "]") { pretty(it) }
	is ByteArray -> a.joinToString(prefix = "[", postfix = "]") { pretty(it) }
	is ShortArray -> a.joinToString(prefix = "[", postfix = "]") { pretty(it) }
	is IntArray -> a.joinToString(prefix = "[", postfix = "]") { pretty(it) }
	is LongArray -> a.joinToString(prefix = "[", postfix = "]") { pretty(it) }
	is FloatArray -> a.joinToString(prefix = "[", postfix = "]") { pretty(it) }
	is DoubleArray -> a.joinToString(prefix = "[", postfix = "]") { pretty(it) }
	is BooleanArray -> a.joinToString(prefix = "[", postfix = "]") { pretty(it) }
	is CharArray -> a.joinToString(prefix = "[", postfix = "]") { pretty(it) }
	is Iterable<*> -> a.joinToString(prefix = "[", postfix = "]") { pretty(it) }
	else -> a.toString()
}
o
👹
j
can't you just use
a::class.java.isArray
?
n
Don't think so, because I do not believe Kotlin will infer a smart cast from that. remember that these
joinToString
are extension functions. Thus, they do need the correct static type in order to work
m
@jakiej with no smart-cast, you can do a stupid-cast an ordinary cast, but there are 9 array types in JVM, so you need also
getComponentType()
simple smile
j
my bad, didn't realize those were extension functions. so you have this many extension functions as well 😱
n
My understanding is that with Kotlin-1.1 (I'm using 1.0.6) I could simplify the code to
Copy code
fun pretty(a: Any?): String = when (a) {
    is Array<*>,
    is ByteArray,
    is ShortArray,
    is IntArray ->,
    is LongArray,
    is FloatArray,
    is DoubleArray,
    is BooleanArray,
    is CharArray,
    is Iterable<*> -> a.joinToString(prefix = "[", postfix = "]") { pretty(it) }
    else -> a.toString()
}
Is that correct?
o
No. Though type check will work (and in 1.0.x also), type of
a
would be
Any
, and you can’t call
joinToString
on it
n
Ahh. So the smart cast casts to the common supertype of all the or-ed options. makes sense