2

I have a method in java just like this and I want to convert it to kotlin. I wrote a method in kotlin but array does not fill and I have null array in return. how can I fix that? Thank in Advance.

Java code

private String[] getNameOfPersonalityTpye(List<PersonalityTpye> list){
        String[] s = new String[list.size()];
        for(int i = 0; i < list.size(); i++){
            s[i] = list.get(i).getPersonalityTypeName();
        }
        return s;
    }

Kotlin code

private fun getNameOfPersonalityTpye(list: List<PersonalityTpye>): Array<String?>{
        val s=  arrayOfNulls<String>(list.size);
        for(i in list.indices){
            s[i] = list[i].name;
        }
        return s;
    }
6
  • Are your sure the list you are passing contains any value? Commented Dec 12, 2018 at 8:36
  • @Dennis Yeah I'm sure. I checked it 2 times Commented Dec 12, 2018 at 8:40
  • Try printing list[i].name in console, do you see anything? Commented Dec 12, 2018 at 8:44
  • @Dennis Yeah, I can see all 4 items in list when I debug it. I'm steel wondering why s array does not fill just like java method Commented Dec 12, 2018 at 8:47
  • I mean did you explicitly println(list[i].name) ? I mean what if it's returning a null value? Commented Dec 12, 2018 at 8:50

3 Answers 3

4

With map and toTypedArray():

private fun getNameOfPersonalityType(list: List<PersonalityType>) = list.map { it.name }.toTypedArray()

I guess it's Type and not Tpye
Just check the size after. If it is 0 then the list was empty.
If the list passed as parameter may contain null values, then change to this:

private fun getNameOfPersonalityType(list: List<PersonalityType?>) = list.mapNotNull { it?.name }.toTypedArray()
Sign up to request clarification or add additional context in comments.

Comments

2

This is working perfectly fine

private fun check(){
        val list = ArrayList<String>()
        list.add("json")
        list.add("statham")
        println("value from array "+getNameOfPersonalityTpye(list)[1]) //prints statham
    }

    private fun getNameOfPersonalityTpye(list:List<String>): Array<String?>{
        val s=  arrayOfNulls<String>(list.size)
        for(i in s.indices){
            s[i] = list[i]
        }
        return s
    }

So this list[i].name; in your code might be null. Otherwise everything is fine.

Comments

0

You can do the following with Stream

private fun getNameOfPersonalityTpye(list: List<PersonalityTpye>): Array<String> {
    return list.stream().map<Any> { e -> e.getPersonalityTypeName() }.toArray() as Array<String>
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.