Bird
0
0

Which of the following is the correct way to declare a variable of type Any in Kotlin?

easy📝 Syntax Q3 of 15
Kotlin - Data Types
Which of the following is the correct way to declare a variable of type Any in Kotlin?
Aval x = null
Bval x: Any = null
Cval x: Any? = 123
Dval x: Any = "Hello"
Step-by-Step Solution
Solution:
  1. Step 1: Check variable declaration rules

    Any is non-nullable, so it cannot hold null. Assigning a string is valid.
  2. Step 2: Analyze each option

    A: val x = null infers Any? - not type Any. B: val x: Any = null assigns null to non-nullable - invalid. C: val x: Any? = 123 declares nullable Any? - not Any. D: val x: Any = "Hello" assigns a string to Any - valid.
  3. Final Answer:

    val x: Any = "Hello" is correct. -> Option D
  4. Quick Check:

    Non-nullable Any must not hold null [OK]
Quick Trick: Any cannot hold null unless declared Any? [OK]
Common Mistakes:
MISTAKES
  • Thinking val x = null declares Any
  • Assigning null to Any type
  • Confusing Any and Any? types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes