Current now, there are two functions in calcite that can be used to cast/convert Expression to a specific Type.
Types.castIfNecessary and RexToLixTranslator.convert.
We make a deep investigation on their implementations and demonstrate them as below.
It can be seen that:
(1) They have a lot of overlaps;
(2) RexToLixTranslator.cast can cover more cases with tools like SqlFunctions and etc.
(3) Both of them have limitations and may generate incorrect code, which is listed in attachment(TypeConversion.txt).
Multiple choices usually bring confusion to developers and resulting to the misuse of them.
CALCITE-3245 exposes that Types.castIfNecessary cannot cast the Expression to BigDecimal.class.
Fixing the issue in Types.castIfNecessary directly seems to be not a good idea.
On one hand, it is not convenient to call SqlFunctions in linq4j. One the other hand, it will brings duplicate with RexToLixTranslator.cast. However, due to some unique logic in Types.castIfNecessary, we cannot replace it as RexToLixTranslator.cast neither.
Therefore, it is a good idea to integrate implementations into RexToLixTranslator.cast.