Defining a UDF
A UDF wraps an ordinary Scala function so it can run as a column expression. Define it with udf(...), then apply it like any built-in. Here's a tiering function that bins an order amount into a label.
import org.apache.spark.sql.functions.udf
val myUdf = udf((x: Double) => /* plain Scala */ )
// then: df.withColumn("out", myUdf($"col"))import org.apache.spark.sql.functions.udf
val tier = udf((amt: Double) =>
if (amt >= 50) "high" else if (amt >= 20) "mid" else "low"
)
orders.select($"product", $"amount", tier($"amount").as("tier"))
.show(false)| product | amount | tier |
|---|---|---|
| Wireless Mouse | 25.0 | mid |
| Notebook | 6.5 | low |
| Mechanical Keyboard | 80.0 | high |
| Desk Lamp | 32.0 | mid |
| Coffee Mug | 12.0 | low |
| USB-C Cable | 9.0 | low |
null itself — Spark passes nulls straight through, and an unguarded UDF will throw a NullPointerException mid-job. Type the input precisely (Double, not Any) so Spark can bind the right column type. And register the return type when it isn't obvious. But before you write any of this — read the next two sections; a UDF is usually the wrong tool.