I am new to language Apex and learning basic stuff. I have follwing code (written for a trailhead challenge) and wondering about the success.
public static Account insertNewAccount(String AccountName) { Account acc = new Account(name = AccountName); try { insert acc; } catch (DmlException e) { acc = null; } return acc; }
The definition of the method says it will return an sObject Account – why is it possible to return a null instead? Are there better ways to declare that method will return Account OR Null?
Answer
Null
can be any type.
So returning a Null
Account
is perfectly valid.
You never need to declare that an Account
will return an Account
OR Null
(and this is not possible) because every complex and primative data type can be Null
.
See here for more information about primitive data types: Primitive Data Types and here: Data Types
More about Null
here:
If you declare a variable and don’t initialize it with a value, it will be null. In essence, null means the absence of a value.
You can also assign null to any variable declared with a primitive type.
Reference here: Variables
Attribution
Source : Link , Question Author : Daniel Koch , Answer Author : Community