【问题标题】:Snowflake Java UDF can't return an array of floats?Snowflake Java UDF 不能返回浮点数组?
【发布时间】:2021-09-30 21:27:41
【问题描述】:

我试图在 Java UDF 中返回浮点数数组,但 Snowflake 抛出错误:

create or replace function float_array_test()
returns array
language java
handler='MyClass.test'
as
$$
    class MyClass {
        public static Float[] test() {
            return new Float[] {1.1, 2.2};
        }
    }
$$;

错误:

100315 (P0000): Error while compiling source: /InlineCode.java:4: error: incompatible types: double cannot be converted to Float
            return new Float[] {1.1, 2.2};

有什么办法解决吗?

【问题讨论】:

    标签: java floating-point snowflake-cloud-data-platform user-defined-functions


    【解决方案1】:

    检查文档以了解允许的类型:float 可以,但 Float 不受支持。

    因此,这是固定的代码:

    create or replace function float_array_test()
    returns array
    language java
    handler='MyClass.test'
    as
    $$
        class MyClass {
            public static float[] test() {
                return new float[] {(float)1.1, (float)2.2};
            }
        }
    $$;
    

    但请注意错误incompatible types: double cannot be converted to Float,这就是为什么我不得不将硬编码的双精度转换为浮动。

    更好的解决方案是在 Java 领域使用双精度数,在 SQL 领域将其转换为浮点数而不会丢失精度:

    create or replace function float_array_test()
    returns array
    language java
    handler='MyClass.test'
    as
    $$
        class MyClass {
            public static double[] test() {
                return new double[] {1.1, 2.2};
            }
        }
    $$;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-20
      • 2022-11-29
      • 1970-01-01
      • 2016-11-25
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      • 2022-12-15
      相关资源
      最近更新 更多