Introduction to Scala UDFs

You can write the handler for a user-defined function (UDF) in Scala. A handler executes as the function’s logic when it’s called in SQL.

Snowflake currently supports writing UDFs in the following versions of Scala:

  • 2.12

Once you have a handler, you create the UDF with SQL. For information on using SQL to create or call a UDF, refer to Creating a UDF or Calling a UDF.

For an introduction to UDFs, including a list of languages in which you can write a UDF handler, refer to User-defined functions overview.

Note

For limitations related to Scala handlers, refer to Scala UDF limitations.

You can also use Scala to write a UDF when using the Snowpark API. For more information, refer to Creating User-Defined Functions (UDFs) for DataFrames in Scala.

How a handler works

When a user calls a UDF, the user passes UDF’s name and arguments to Snowflake. Snowflake calls the handler method associated with the UDF to execute the UDF’s logic. The handler method then returns the output to Snowflake, which passes it back to the client.

For a scalar function (one that returns a single value), the UDF returns a single value for each row passed to the UDF.

To support your handler’s logic, your code can make calls to libraries that are external to the handler. For example, if you already have data analysis code in Scala, then you can probably use it from your handler code.

For general information on writing a handler in Scala, refer to General Scala UDF handler coding guidelines. For information on writing a scalar function, refer to Writing a scalar UDF in Scala.

Example

Code in the following example creates a UDF called echo_varchar with a handler method TestFunc.echoVarchar. The Scala argument and return types are converted to and from SQL by Snowflake according to mappings described in SQL-Scala Data Type Mappings.

CREATE OR REPLACE FUNCTION echo_varchar(x VARCHAR)
RETURNS VARCHAR
LANGUAGE SCALA
RUNTIME_VERSION = 2.12
HANDLER='TestFunc.echoVarchar'
AS
$$
class TestFunc {
  def echoVarchar(x : String): String = {
    return x
  }
}
$$;
Copy

Call the UDF

SELECT echo_varchar('Hello');
Copy

Design considerations

Keep in mind the following for designing a useful handler.

Handler coding

From basics to detailed examples, the following topics describe how to write a UDF handler in Scala.

Language: English