惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Jina AI
Jina AI
Recent Announcements
Recent Announcements
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
A
About on SuperTechFans
Vercel News
Vercel News
博客园 - 【当耐特】
爱范儿
爱范儿
Blog — PlanetScale
Blog — PlanetScale
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
D
Docker
博客园 - 叶小钗
The Cloudflare Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
H
Help Net Security
I
InfoQ
博客园 - 三生石上(FineUI控件)
博客园 - Franky
Microsoft Azure Blog
Microsoft Azure Blog
The GitHub Blog
The GitHub Blog
大猫的无限游戏
大猫的无限游戏
MongoDB | Blog
MongoDB | Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
What Is a Function in Scala
Daniel Toni · 2026-05-31 · via DEV Community

One of the most important concept in Scala and Functional Programming, is that functions are first-class values. This means functions are treated as any other data type in the language: they can be assigned to variables, passed as arguments to other functions, and returned from functions.

Treating functions as first-class values enables powerful code design capabilities, such as:

  1. Higher-Order Functions
  2. Function Composition
  3. Closures and Currying

The way Scala achieves this feature is by treating functions as objects, instances of a class, just like String, Int or any other type.

A function is an object with one method.

First, let's look at the long way of building a function value. We can define a generic trait called MyFunction that takes a parameter of type A and returns a value of type B. This trait will expose an apply method:

trait MyFunction[A, B] {
  def apply(arg: A): B
}

We can then create a variable and instantiate an anonymous class using this trait:

val doubler = new MyFunction[Int, Int] {
  override def apply(arg: Int): Int = arg * 2
}

val randomNumber: Int = 14

doubler.apply(randomNumber) // 28

Notice how doubler is an object with an apply method. The Scala compiler provides syntactic sugar that allows us to omit the explicit .apply invocation, resulting in doubler(randomNumber). This matches the exact syntax we use to call methods, making every function value look and feel callable.

Fortunately, we don't need to define these traits ourselves. The Scala standard library provides built-in traits named FunctionX, such as Function1[A, B] and Function2[A, B, C]. The number in the trait name represents how many parameters the function accepts. Thus, our custom MyFunction[A, B] is functionally equivalent to Function1[A, B] (though the standard library traits bundle additional useful helper methods).

To illustrate this with multiple parameters, here is how we create a function that adds two integers:

val adder = new Function2[Int, Int, Int] {
  override def apply(a: Int, b: Int): Int = a + b
}

val anotherNumber: Int = 12

adder(randomNumber, anotherNumber) // 26

This demonstrates that every function value under the hood is an instance of a built-in FunctionX trait.

The => syntactic sugar for function types

Writing out FunctionX can become verbose. To make code more concise, the Scala compiler provides syntactic sugar using the => operator to define function types:

Int => Int                 // sugar for Function1[Int, Int]
(Int, Int) => Int          // sugar for Function2[Int, Int, Int]

Using this notation, our adder definition becomes:

val adder = new ((Int, Int) => Int) {
  override def apply(a: Int, b: Int): Int = a + b
}

Defining function values with function literals

While the anonymous class syntax works, Scala offers an even cleaner way to produce the exact same object: function literals (also known as lambda expressions).

val doubler = (arg: Int) => arg * 2

val adder = (a: Int, b: Int) => a + b

Though the syntax is completely different, the end result is identical. The compiler abstracts away the boilerplate, instantiating the appropriate FunctionX trait under the hood and overriding the apply method with your function's body. We write the logic, and the compiler writes the new ... { override def apply... } boilerplate for us.

Functions as first-class values

Because functions are objects, we can effortlessly pass them as arguments to other functions:

List(1, 2, 3).map(doubler)

or

List(1, 2, 3).map(n => n * 2)

def vs val

It is important not to mix up two distinct concepts: val functions and def methods. While we often call both "functions", they behave differently under the hood:

A val holds data, an instance of a FunctionX object.

A def defines a method. A method belongs to a class or object, does not hold data on its own, and is not an instance of FunctionX.

When you pass a method to a place that expects a function value, the compiler automatically converts that method into a function object. This mechanism is called Eta-expansion. (I will discuss in a future post).

Summary

A function in scala is an object, an instance of a FunctionX trait whose job is its apply method. => is sugar for the type, f(x) is sugar for f.aaply(x), and a function literal is a concise shorthand the compiler translates into a full function object at runtime