1
fun main() {
val arr = arrayOf("hello",3,true)
for(item in arr) if(item is Int)  println(item + 20 )
// print(arr[1] + 20)
}

I created an array of String, Int and Boolean.
I can do the summation in the for-loop. However, if I am trying to do the print(arr[1] + 20) there is an "Unresolved reference" problem. Can someone explain this to me? Thanks.

2
  • Also, in general, it's not a great idea to have item of different type in an array, Commented May 7, 2021 at 14:46
  • “I created an array of String, Int and Boolean”.  What you actually created is an Array<Any> (that just happened to initially contain a String, an Int, and a Boolean).  When you pull out a value, all the compiler knows is that it's an Any — unless you check it yourself, as you do within the loop.  But that doesn't tell you anything about it outside the loop. Commented May 7, 2021 at 18:29

2 Answers 2

1

As you've said, the array contains mixed types, so the compiler can't infer that arr[1] is an integer. The difference in your loop is that you explicitly check that item is an integer, so it can do what is called a smart cast.

Therefore you would either have to cast it, or reconsider your structure, which might be a better choice. You probably want a class here that can hold a string, integer and boolean.

Sign up to request clarification or add additional context in comments.

Comments

0

You may think that youbare trying to do Int + Int. But the array is of type Any. Therefore you have Any + Int which is not a valid function. You could do (arr[1] as Int) + 20

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.