How to initialize Kotlin IntArray from IntRange? - kotlin

I'm trying to initialize an IntArray in Kotlin like so:
intArrayOf(1..9)
But I get a TypeError that Int is required, but I'm providing an IntRange. Is there a way to initialize the array with a range, or do I have to explicitly write out each value?

Using built in functions, this is how you could get to an IntArray from an IntRange:
val array: IntArray = (1..9).toList().toIntArray()
This is a bit wasteful, because it first constructs a list where it puts all the elements, and then it constructs an array as well. To do this directly, you could use your own extension, something like...
fun IntRange.toIntArray(): IntArray {
if (last < first)
return IntArray(0)
val result = IntArray(last - first + 1)
var index = 0
for (element in this)
result[index++] = element
return result
}
Which would give you this syntax:
val array: IntArray = (1..9).toIntArray()

Related

Initializing a list in kotlin

I am trying to initlaise a list as part of a constructor argument. But I do not understand what it wants from me
distortion = List(
size = 10,
init = 0
)
The list is of type room entity
var distortion: List<DistortionCacheEntity>? = null
The init part is underlined in red. I dont know what to put in there or how to write it. Could someone help.
The function you are trying to invoke looks like this:
public inline fun <T> List(size: Int, init: (index: Int) -> T): List<T>
So init here is not an Integer but rather a function. Invoke like so:
distortion = List(size = 10) { index : Int ->
//Create object that the list needs to hold
}
var distortion: List<DistortionCacheEntity>? = null
distortion = List(10) { index -> DistortionCacheEntity()}
The simplest way to initialize a list is with kotlin library function listOf(...)
For example,
listOf(1, 2, 3) // [1, 2, 3]

How to create variables in a for-loop with Kotlin

Given a maximum list size in parameter size and total amount of elements in parameter elements, I need to create a list of lists. What is the syntax for creating variables in for loops in Kotlin?
The way I'm thinking of going about this is to declare and create lists before elements are added to a list. Then, when a list has reached full capacity, it is switched out for the next list that is empty.
Here is the half-baked code:
fun listOfLists(size: Int, vararg elements: String): List<List<String>> {
var amountOfElements = elements.size
var currentSubList: List<String> = mutableListOf<String>()
val numberOfLists: Int = amountOfElements / size + 1
for (n in 0..numberOfLists) {
// Code for creating the total number of lists needed
}
for (e in elements) {
if (amountOfElements % size == 0) {
// Code for switching lists
}
amountOfElements--
}
As #dyukha correctly mentioned, what you need is chunked() function.
fun listOfLists(size: Int, vararg elements: String) =
elements.asList().chunked(size)
Or, if you want to be really efficient, you can also use asSequence():
fun listOfLists(size: Int, vararg elements: String) =
elements.asSequence().chunked(size)
chunked() doesn't work on Array, because it's defined on Iterable and Sequence, and Array doesn't implement any of them.

deal with arrays of Kotlin with Long variables

I have a question about Kotlin.
I tried two versions of Kotlin, 1.0.0 and 1.2.6.
Using Kotlin, we can initialize an array and access to its element like this.
val n: Int = 10
val arr = Array(n, { it } )
val i: Int = 0
println(arr[i])
However, I got an error with this code.
val n: Long = 10
val arr = Array(n, { it } )
val i: Long = 0
println(arr[i])
It seems that it is an only way to cast Long to Int in order to compile this code.
val n: Long = 10
val arr = Array(n.toInt(), { it } )
val i: Long = 0
println(arr[i.toInt()])
However, it seems too redundant to me, but I couldn't find any solutions. So my question is
Is there any way to initialize arrays and access elements with a Long
variable?
Does Kotlin have any reasons that Long variable should not be accepted here?
Kotlin comes with longArrayOf(1, 2, 3) which will create an array for you which contains Longs.
Note that what you are trying to do with println(arr[i]) is getting a Long value out of arr, but the indexing of arrays is done with Ints. It will never work with Longs:
/**
* Returns the array element at the given [index].
* This method can be called using the index operator.
*/
public operator fun get(index: Int): Long
If you want to initialize an array of longs of the given length, you can use the same top-level Array function:
val n = 10 // n is Int
val arrayOfLongs = Array(n) { it.toLong() } // Array of 10 longs
Here the number n is Int and the initializer function converts the integer index it of an element being initialized to Long, therefore we get an array of longs as the result.
Or you can use another similar function to create a specialized LongArray:
val longArray = LongArray(n) { it.toLong() } // LongArray of 10 longs
Both arrays store longs, but the latter does it more compactly.

How can I use a Java String method (split) directly from Kotlin source?

Doing some profiling, it seems my bottleneck is the Kotlin kotlin.CharSequence.split() extension function.
My code just does something like this:
val delimiter = '\t'
val line = "example\tline"
val parts = line.split(delimiter)
As you might notice, parts is a List<String>.
I wanted to benchmark using Java's split directly, which returns a String[] and might be more efficient.
How can I call Java's String::split(String) directly from Kotlin source?
You can cast a kotlin.String to a java.lang.String then use the java.lang.String#split since kotlin.String will be mapped to java.lang.String , but you'll get a warnings. for example:
// v--- PLATFORM_CLASS_MAPPED_TO_KOTLIN warnings
val parts: Array<String> = (line as java.lang.String).split("\t")
You also can use the java.util.regex.Pattern#split instead, as #Renato metioned it will slower than java.lang.String#split in some situations. for example:
val parts: Array<String> = Pattern.compile("\t").split(line, 0)
But be careful, kotlin.String#split's behavior is different with java.lang.String#split , for example:
val line: String = "example\tline\t"
// v--- ["example", "line"]
val parts1: Array<String> = Pattern.compile("\t").split(line, 0)
// v--- ["example", "line", ""]
val parts2 = line.split("\t".toRegex())
You can do this:
(line as java.lang.String).split(delimiter)
But it's not recommended to not use the kotlin.String as the compiler might tell you.

How can I tell Kotlin that an array or collection cannot contain nulls?

If I create an array, then fill it, Kotlin believes that there may be nulls in the array, and forces me to account for this
val strings = arrayOfNulls<String>(10000)
strings.fill("hello")
val upper = strings.map { it!!.toUpperCase() } // requires it!!
val lower = upper.map { it.toLowerCase() } // doesn't require !!
Creating a filled array doesn't have this problem
val strings = Array(10000, {"string"})
val upper = strings.map { it.toUpperCase() } // doesn't require !!
How can I tell the compiler that the result of strings.fill("hello") is an array of NonNull?
A rule of thumb: if in doubts, specify the types explicitly (there is a special refactoring for that):
val strings1: Array<String?> = arrayOfNulls<String>(10000)
val strings2: Array<String> = Array(10000, {"string"})
So you see that strings1 contains nullable items, while strings2 does not. That and only that determines how to work with these arrays:
// You can simply use nullability in you code:
strings2[0] = strings1[0]?.toUpperCase ?: "KOTLIN"
//Or you can ALWAYS cast the type, if you are confident:
val casted = strings1 as Array<String>
//But to be sure I'd transform the items of the array:
val asserted = strings1.map{it!!}
val defaults = strings1.map{it ?: "DEFAULT"}
Why the filled array works fine
The filled array infers the type of the array during the call from the lambda used as the second argument:
val strings = Array(10000, {"string"})
produces Array<String>
val strings = Array(10000, { it -> if (it % 2 == 0) "string" else null })
produces Array<String?>
Therefore changing the declaration to the left of the = that doesn't match the lambda does not do anything to help. If there is a conflict, there is an error.
How to make the arrayOfNulls work
For the arrayOfNulls problem, they type you specify to the call arrayOfNulls<String> is used in the function signature as generic type T and the function arrayOfNulls returns Array<T?> which means nullable. Nothing in your code changes that type. The fill method only sets values into the existing array.
To convert this nullable-element array to non-nullable-element list, use:
val nullableStrings = arrayOfNulls<String>(10000).apply { fill("hello") }
val strings = nullableStrings.filterNotNull()
val upper = strings.map { it.toUpperCase() } // no !! needed
Which is fine because your map call converts to a list anyway, so why not convert beforehand. Now depending on the size of the array this could be performant or not, the copy might be fast if in CPU cache. If it is large and no performant, you can make this lazy:
val nullableStrings = arrayOfNulls<String>(10000).apply { fill("hello") }
val strings = nullableStrings.asSequence().filterNotNull()
val upper = strings.map { it.toUpperCase() } // no !! needed
Or you can stay with arrays by doing a copy, but really this makes no sense because you undo it with the map:
val nullableStrings = arrayOfNulls<String>(10000).apply { fill("hello") }
val strings: Array<String> = Array(nullableStrings.size, { idx -> nullableStrings[idx]!! })
Arrays really are not that common in Java or Kotlin code (JetBrains studied the statistics) unless the code is doing really low level optimization. It could be better to use lists.
Given that you might end up with lists anyway, maybe start there too and give up the array.
val nullableStrings = listOf("a","b",null,"c",null,"d")
val strings = nullableStrings.filterNotNull()
But, if you can't stop the quest to use arrays, and really must cast one without a copy...
You can always write a function that does two things: First, check that all values are not null, and if so then return the array that is cast as not null. This is a bit hacky, but is safe only because the difference is nullability.
First, create an extension function on Array<T?>:
fun <T: Any> Array<T?>.asNotNull(): Array<T> {
if (this.any { it == null }) {
throw IllegalStateException("Cannot cast an array that contains null")
}
#Suppress("CAST_NEVER_SUCCEEDS")
return this as Array<T>
}
Then use this function new function to do the conversion (element checked as not null cast):
val nullableStrings = arrayOfNulls<String>(10000).apply { fill("hello") }
val strings = nullableStrings.asNotNull() // magic!
val upperStrings = strings.map { it.toUpperCase() } // no error
But I feel dirty even talking about this last option.
There is no way to tell this to the compiler. The type of the variable is determined when it is declared. In this case, the variable is declared as an array that can contain nulls.
The fill() method does not declare a new variable, it only modifies the contents of an existing one, so it cannot cause the variable type to change.