How to get KtClass from PsiElement or VirtualFile? - intellij-plugin

I want to make an plugin that generate some template code for some specific kotlin files. Now I need to get KtClass from PsiElement or VirtualFile. I tried some code as below, but it's not working.
val psiFile = e.getData(CommonDataKeys.PSI_FILE)
psiFile ?: return
val editor = e.getData(CommonDataKeys.EDITOR)
editor ?: return
println(psiFile.name)
val pe = psiFile.findElementAt(editor.caretModel.offset)
if (pe != null) {
println(pe.text)
} else {
println("PE is null")
}
val kt = PsiTreeUtil.getParentOfType(pe, KtClass::class.java)
kt?.run {
println(this.text)
}
PS: I found that there are 2 PsiTreeUtils, one from org.jetbrains.kotlin.com.intellij.psi.util package, and another from com.intellij.psi.util, I don't know which one should I use

A PsiFile might contain zero or more KtClasss. You can get them all by doing this:
val classes = psiFile.getChildrenOfType<KtClass>().asList()

Related

Why is "contains" or "in" not working in Kotlin

I'm currently working on a project with different functions.
One of the functions is supposed to take a map and a string as inputs, then compare the items in the map and string and create a new map with matching items.
This function is not working because "containsKey" always returns false.
"in" always returns fault.
I tried substituting the map with a mutable List and got the same results.
I tried this same code on kotlin playground, link; https://pl.kotl.in/zZm1Smz3Z
and it worked well but wouldn't work on the platform I am using.
The function is below
fun createVariable (stringList: String, mapNumber: MutableMap<String, String>):MutableMap<String, String> {
var mapOfNumber = mutableMapOf<String, String>()
var conList : MutableList<String> = mutableListOf()
var regex = Regex("\\s*=\\s*")
var regez = Regex("\\s+")
var numberList = stringList.split(regex).toMutableList()
for (i in 0.. numberList.size -1) {
if ( regez.matches(numberList[i])) {
numberList.removeAt(i)
}
}
if (mapNumber.containsKey(numberList[1])) {
mapOfNumber.put(numberList[0], (mapNumber[numberList[1]])?: "0")
}
print(mapOfNumber)
return mapOfNumber
}

Mapping array elements using a function in Kotlin

New to Kotlin from Python. In Python, I can simply use the code below to pass each element of a List to a multiline function and return an iterator of the result.
countArr = list(map(countReps, arr))
In Kotlin, I found that I had to do the following. Am I missing something?
fun LetterCountI(str: String): String {
val arr = str.split(" ")
var transform:(String) -> Int = {countReps(it)}
val countArr = arr.map(transform)
val mxIndex:Int
var ans:String
if (countArr.max()!=1){
mxIndex = countArr.indexOf(countArr.max())
ans = arr[mxIndex]
} else {
ans = "-1"
}
return ans;
}
fun countReps(str: String): Int {
var m = mutableMapOf<Char, Int>()
var v:Int
for (c in str){
if (c in m.keys){
v = m[c]?:0
m.put(c,v+1)
} else {
m.put(c,1)
}
}
return m.values.max() ?: 0
}```
I'm having a bit of a hard time understanding your code, but one thing I can tell you is that you can replace
var transform:(String) -> Int = {countReps(it)}
val countArr = arr.map(transform)
with
val countArr = arr.map(::countReps)
In addition to the line you ask about, just about all of that code could be rewritten more concisely and idiomatically in Kotlin. For example:
fun String.wordWithMostRepeatedLetters()
= split(" ")
.associateWith{ it.maxRepeatedLetters() }
.filter{ it.value > 1 }
.maxByOrNull{ it.value }?.key ?: "-1"
fun String.maxRepeatedLetters()
= groupBy{ it }.map{ it.value.size }.maxOrNull() ?: 0
I've renamed the functions to try to explain what they give; replaced the countArr list with a map from each word to its count, so that you don't need to re-scan it to find the word resulting; and changed both functions to take a String receiver instead of a parameter. Then, because each variable was only used once, I removed them and made it all in-line, using an expression body for each function.
Some of those things don't always improve clarity, of course, especially for long functions — but I hope it demonstrates how concise Kotlin can be. (Hopefully without sacrificing maintainability. Which version would be easier to read? Which would be more likely to harbour subtle bugs?)
It's still not clear what the hard-coded "-1" return value indicates, though… If no word has any repeated letters, a null return would be more idiomatic. (Or it would be simpler just to return the first word, removing the filter() call, and returning null only if the string is blank.)

Kotlin combine lists based on common property

I have two functions (GetPodsOne and GetPodsTwo) that return me a big csv string. I then do some processing to discard the part of the string I don't want. See snippet below.
var podValues = execGetPodsOne()
val testPodValuesLst: List<String> = podValues.split(",").map { it -> it.substringAfterLast("/") }
testPodValuesLst.forEach { it ->
 println("value from testPodList=$it")
 }
podValues = execGetPodsTwo()
val sitPodValuesLst: List<String> = podValues.split(",").map { it -> it.substringAfterLast("/") }
sitPodValuesLst.forEach { it ->
 println("value from sitPodList=$it")
 }
This leaves me with two lists. See output of the above below:
value from testPodList=api-car-v1:0.0.118
value from testPodList=api-dog-v1:0.0.11
value from testPodList=api-plane-v1:0.0.36
value from sitPodList=api-car-v1:0.0.119
value from sitPodList=api-dog-v1:0.0.12
value from sitPodList=api-plane-v1:0.0.37
What i would like to do is end up with the objects inside a data class like below:
data class ImageVersions(val apiName: String, val testPodVersion: String, val sitPodVersion: String)
api-car-v1, 0.0.118, 0.0.119
api-dog-v1, 0.0.11, 0.0.12
api-plane-v1, 0.0.36, 0.0.37
I've used test and sit above but I'm going to have maybe another 5 environments eventually. Looking for a nice way to get the versions for each api and easily combine into that ImageVersions data class.
thanks
Considering that you're going to have maybe another 5 environments eventually, I tried to write something that will scale well:
enum class Env { Test, Sit }
data class ImageVersions(val apiName: String, val versions: Map<Env, String?>)
fun String.getNameAndVersion() = substringBefore(':') to substringAfter(':')
fun getVersions(envMap: Map<Env, List<String>>): List<ImageVersions> {
val envApiNameMap = envMap.mapValues { it.value.associate(String::getNameAndVersion) }
val allApiNames = envApiNameMap.flatMap { it.value.keys }.distinct()
return allApiNames.map { apiName ->
ImageVersions(apiName, envApiNameMap.mapValues { it.value[apiName] })
}
}
Playground example
So instead of separate val testPodVersion: String, val sitPodVersion: String, here you have a map. Now the structure of ImageVersions always remains the same irrespective of how many environments you have.
getNameAndVersion is a helper function to extract apiName and version from the original string.
getVersions accepts a list of versions corresponding to each environment and returns a list of ImageVersions
envApiNameMap is same as envMap just that the list is now a map of apiName and its version.
allApiNames contains all the available apiNames from all environments.
Then for every apiName, we take all the versions of that apiName from all the environments.
In future, if your have another environment, just add it in the Env enum and pass an extra map entry in the envMap of getVersions. You need not modify this function every time you have a new environment.
How about this:
val testPodValuesMap = testPodValuesLst.associate { it.split(':').zipWithNext().single() }
val sitPodValuesMap = sitPodValuesLst.associate { it.split(':').zipWithNext().single() }
val mergedMap = (testPodValuesMap.keys + sitPodValuesMap.keys).associateWith { key ->
testPodValuesMap.getValue(key) to sitPodValuesMap.getValue(key)
}
val imageVersions = mergedMap.map { (k, v) -> ImageVersions(k, v.first, v.second) }
println(imageVersions.joinToString("\n"))
which prints
ImageVersions(apiName=api-car-v1, testPodVersion=0.0.118, sitPodVersion=0.0.119)
ImageVersions(apiName=api-dog-v1, testPodVersion=0.0.11, sitPodVersion=0.0.12)
ImageVersions(apiName=api-plane-v1, testPodVersion=0.0.36, sitPodVersion=0.0.37)
As a first step I would extract the apiNames from both lists:
val apiNames = list1.map { it.replace("value from ", "").split("[=:]".toRegex())[1] }
.plus(list2.map { it.replace("value from ", "").split("[=:]".toRegex())[1] })
.distinct()
Then I'd create the ImageVersions instances by looping over apiNames:
val result = apiNames
.map { apiName ->
ImageVersions(
apiName,
(list1.firstOrNull { it.contains(apiName) } ?: "").split(":")[1],
(list2.firstOrNull { it.contains(apiName) } ?: "").split(":")[1]
)
}
.toList()
The reason to first extract the apiNames is, that apiNames missing in one of the two lists will still end up in the final result.
Kotlin Playground

Kotlin / value passing to List<>()

I have a question in List<Contact>() I'm asked to pass init and size. I'm not sure if it's obligated to pass it as in my following tutorial ArrayList<String>() was empty, maybe it's because I was using List<>? Also, it doesn't recognize lowercase() and add() is it also related to List<>?
Code Snippet
val contacts = remember { DataProvider.contactList }
var filteredContacts: List<Contact>
val textState = remember { mutableStateOf(TextFieldValue("")) }
LazyColumn(
...
) {
val searchText = textVal.value.text
filteredContacts = if (searchText.isEmpty()){
contacts
}
else{
val resultList = List<Contact>()
for (contact in contacts) {
if (contact.lowercase(Locale.getDefault()).contains(searchText.lowercase(Locale.getDefault()))) {
resultList.add(contact)
}
}
resultList
}
In kotlin, List has no add method. For that you would need to have a MutableList.
Regarding lowercase method, this is available for Strings. You are trying to apply that to a Contact object, which I guess has no lowercase method.

how to convert a String sentence to arraylist in Kotlin

I have this function to convert string sentence to list words. I created this function in Java and converted to Kotlin using default Kotlin conversion in Android Studio, but I believe there can be many ways to shorten this code in Awesome Kotlin. I will be good if you can share your piece of code and help me(and all) to improve our knowledge in Kotlin.
private fun stringToWords(mnemonic: String): List<String> {
val words = ArrayList<String>()
for (word in mnemonic.trim { it <= ' ' }.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) {
if (word.isNotEmpty()) {
words.add(word)
}
}
return words
}
I would go for the following:
fun stringToWords(s : String) = s.trim().splitToSequence(' ')
.filter { it.isNotEmpty() } // or: .filter { it.isNotBlank() }
.toList()
Note that you probably want to adjust that filter, e.g. to filter out blank entries too... I put that variant in the comment... (if you use that one, you do not require an initial trim() though)
If you rather want to work with the Sequence you can do so by just omitting the .toList() at the end.
And as also Abdul-Aziz-Niazi said: same is also possible via extension function, if you require it more often:
fun String.toWords() = trim().splitToSequence(' ').filter { it.isNotEmpty() }.toList()
You can do it like this.. Just make a function of return type list.
val s = "This is a sample sentence."
val words:Array<String> = s.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (i in words.indices) {
// You may want to check for a non-word character before blindly
// performing a replacement
// It may also be necessary to adjust the character class
words[i] = words[i].replace("[^\\w]".toRegex(), "")
}
May this will help you :-)
It's easier than you think:
fun stringToWords(mnemonic: String) = mnemonic.replace("\\s+".toRegex(), " ").trim().split(" ")
Remove multiple spaces, trim start and the end, split.
Like an extention:
fun String.toWords() = replace("\\s+".toRegex(), " ").trim().split(" ")
After Roland's suggestion:
fun String.toWords() = trim().split("\\s+".toRegex())
You don't need scopes, the redundant "".toRegex() and the last expression.
You can do something like this:
private fun stringToWords(mnemonic: String): List<String> {
val words = ArrayList<String>()
for (w in mnemonic.trim(' ').split(" ")) {
if (w.isNotEmpty()) {
words.add(w)
}
}
return words
}
Additionally,
If you use this method a lot in this project, you can make it an extension in string class. Paste this method in a separate file(outside a classes or add it in classless .kt file) so it has a global access.
and then you can use it with any string like
myString.toWords() anywhere in the project
The method will look like this
inline fun String.toWords(): List<String> {
val words = ArrayList<String>()
for (w in this.trim(' ').split(" ")) {
if (w.isNotEmpty()) {
words.add(w)
}
}
return words
}