Explanation:
In programming, the concept of “contextual type” refers to the type of an expression that can be inferred from its surrounding context. In other words, the type of a variable or expression can be determined based on how it is being used in the code.
When the error message says “‘nil’ requires a contextual type,” it means that the compiler or interpreter expects a specific type for the symbol or expression ‘nil’ based on the context in which it is being used.
Here’s an example to illustrate this:
// Let's assume we are using a programming language with static typing
// and the following code is written in that language.
var age = nil; // Error: 'nil' requires a contextual type
// In this example, we are trying to assign 'nil' to a variable called 'age'.
// However, the compiler throws an error because it cannot infer the type of 'age'
// based on the context. It needs additional information to determine the type.
// To fix this error, we need to provide a contextual type explicitly:
var age: Int? = nil; // 'age' is of optional Int type, initialized with 'nil'
// Now, the compiler understands that 'age' is an optional integer type (Int?).
// By specifying the contextual type explicitly, we resolve the error.
// Alternatively, the contextual type can be inferred by assigning a value to the variable:
var age = 25; // 'age' is inferred as an integer type (Int)
// In this case, the compiler knows that 'age' should be of type Int because we
// assigned an integer value to it. 'nil' is not a valid integer value, hence,
// the error doesn't occur.