蓝色天空网mbsky.com · 知识 · 实践 · 创造Kotlin · 本地阅读预览
教程 / 移动开发 / Kotlin

Kotlin 接口

详解 Kotlin 接口的抽象与默认方法、多接口实现、无幕后字段的接口属性与默认 getter、super<接口名> 冲突与菱形继承消歧、接口与抽象类对比及 Kotlin 1.4+ fun interface SAM 转换。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

接口定义、默认方法与多接口实现

Kotlin 使用 `interface` 定义能力契约,既可声明抽象方法,也可直接编写带方法体的默认实现(且默认方法内部可调用同接口的抽象方法)。与普通类成员默认 `final` 相反,接口成员默认是 `public` 且 `open` 的;默认实现使接口向后兼容地新增方法时不会破坏既有实现类。

类通过在冒号后列出接口名来实现接口(有主构造器时构造参数写在冒号之前),具体类必须实现全部抽象成员否则需声明为 `abstract`。单个类可通过逗号分隔同时实现多个接口,从而弥补单继承限制,并可将不同实现统一放入 `List<Named>` 多态处理。

接口属性规则:抽象属性与默认 getter

接口不保存对象状态,因此接口属性不能拥有幕后字段(backing field),也不能编写字段初始化器(例如 `val name: String = "MBSKY"` 会直接编译报错)。重点澄清:接口属性并非只能是抽象的——除抽象 `val`/`var` 外,完全可以声明带默认 `get()` 的计算属性(如 `val displayName: String get() = "[$name]"`),实现类可直接继承复用。

多接口冲突消歧、菱形接口继承与抽象类对比

当多个接口提供同名方法或属性的默认实现时,实现类必须显式重写并通过 `super<A>.foo()`、`super<B>.label` 分别指定目标接口实现;若仅一方有默认实现、另一方仅为抽象声明则不构成默认实现冲突(仍需显式重写以满足多超类型契约)。接口也可继承一个或多个父接口,形成菱形继承时若子接口改写了默认实现,最终实现类同样需显式 `override` 并用 `super<Right>.base()` 消歧。

在接口与抽象类之间选型时遵循经验法则:表达跨类型的能力契约(can-do)且不保存可变状态时选接口;需要构造器、幕后字段共享状态或表达严格 is-a 层次时选抽象类。

函数式接口 fun interface 与常见问题

自 Kotlin 1.4 起,使用 `fun interface` 声明仅含唯一抽象方法的函数式接口(允许同时包含带实现的非抽象辅助方法),即可直接通过 Lambda 触发 SAM 转换创建实例(如 `val notEmpty = Validator { it.isNotEmpty() }`)。普通接口即便只有一个抽象方法也不支持 SAM 转换;此外编译器限制 `fun interface` 的唯一抽象方法不能是 `suspend` 函数。

常见五问:接口属性不能写初始化器因接口无状态与幕后字段;接口成员默认 `open` 而非 `final`;类可用逗号实现多接口并以 `super<接口名>` 消歧;接口不能有构造器;仅 `fun interface`(Kotlin 1.4+)支持 Lambda 直接构造实例。

Kotlin 接口与抽象类核心对比

对比项接口抽象类
能否保存状态不能,属性不可拥有幕后字段可以,属性可拥有幕后字段与初始化器
能否有构造器不能可以有主构造器和次构造器
多继承一个类可同时实现多个接口一个类只能继承一个抽象类
成员默认可见性public,且默认 openpublic,普通成员默认 final
默认实现支持,方法可带方法体、属性可带 getter支持,直接编写普通成员实现
典型用途定义能力契约,跨类型共享行为共享状态与公共实现,表达 is-a 关系

离线校验接口默认方法、无幕后字段属性、菱形 super<Interface> 消歧与 fun interface

python · 阅读源码
"""Offline Kotlin 2.x semantic verifier for Chapter 19 (interface)."""
from abc import ABC, abstractmethod
import json
import sys
from typing import Callable

VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"


class SiteIface(ABC):
    @abstractmethod
    def name(self) -> str:
        ...

    def url(self) -> str:
        return "www.mbsky.com"

    def info(self) -> str:
        return f"站点:{self.name()},地址:{self.url()}"


class FullSite(SiteIface):
    def name(self) -> str:
        return "MBSKY"

    def url(self) -> str:
        return "https://www.mbsky.com"


class SimpleSite(SiteIface):
    def name(self) -> str:
        return "Mbsky"


class NamedProp(ABC):
    @property
    @abstractmethod
    def name(self) -> str:
        ...

    @property
    def display_name(self) -> str:
        return f"[{self.name}]"

    @property
    @abstractmethod
    def visits(self) -> int:
        ...

    @visits.setter
    @abstractmethod
    def visits(self, value: int) -> None:
        ...


class SitePropImpl(NamedProp):
    def __init__(self, name: str) -> None:
        self._name = name
        self._visits = 0

    @property
    def name(self) -> str:
        return self._name

    @property
    def visits(self) -> int:
        return self._visits

    @visits.setter
    def visits(self, value: int) -> None:
        self._visits = value


class A:
    def foo(self) -> str:
        return "A.foo"

    @property
    def label(self) -> str:
        return "A.label"


class B:
    def foo(self) -> str:
        return "B.foo"

    @property
    def label(self) -> str:
        return "B.label"


class C(A, B):
    def foo(self) -> str:
        return A.foo(self) + " | " + B.foo(self)

    @property
    def label(self) -> str:
        return A.label.fget(self) + " | " + B.label.fget(self)  # type: ignore[misc]


class Base:
    def base(self) -> str:
        return "Base"


class Left(Base):
    def left(self) -> str:
        return "Left"


class Right(Base):
    def base(self) -> str:
        return "Right 重写了 Base"

    def right(self) -> str:
        return "Right"


class DiamondImpl(Left, Right):
    def base(self) -> str:
        return Right.base(self)


class Validator:
    """Models Kotlin 1.4+ `fun interface Validator` with one abstract method + default helper."""

    def __init__(self, fn: Callable[[str], bool]) -> None:
        self._fn = fn

    def validate(self, text: str) -> bool:
        return self._fn(text)

    def describe(self) -> str:
        return "校验器"


def run_cases() -> list[dict]:
    cases: list[dict] = []

    # Case 1: Interface abstract + default methods & polymorphic list
    actual_1 = {
        "full_override": FullSite().info(),
        "default_inherited": SimpleSite().info(),
        "interface_members_default_public_open": True,
        "interface_can_have_constructor": False,
    }
    expected_1 = {
        "full_override": "站点:MBSKY,地址:https://www.mbsky.com",
        "default_inherited": "站点:Mbsky,地址:www.mbsky.com",
        "interface_members_default_public_open": True,
        "interface_can_have_constructor": False,
    }
    cases.append({
        "name": "interface_default_methods_and_impl",
        "summary": "Verify interface abstract/default methods, default public+open semantics, and multiple implementation.",
        "expected": expected_1,
        "actual": actual_1,
        "passed": actual_1 == expected_1,
    })

    # Case 2: Interface properties (abstract val/var + default getter, no backing field/initializer)
    sp = SitePropImpl("MBSKY")
    sp.visits = 100
    actual_2 = {
        "default_getter_display_name": sp.display_name,
        "impl_var_visits": sp.visits,
        "interface_property_allows_backing_field": False,
        "interface_property_allows_initializer": False,
    }
    expected_2 = {
        "default_getter_display_name": "[MBSKY]",
        "impl_var_visits": 100,
        "interface_property_allows_backing_field": False,
        "interface_property_allows_initializer": False,
    }
    cases.append({
        "name": "interface_properties_no_backing_field",
        "summary": "Verify interface abstract properties, default getter properties, and prohibition of backing fields/initializers.",
        "expected": expected_2,
        "actual": actual_2,
        "passed": actual_2 == expected_2,
    })

    # Case 3: Multi-interface conflict disambiguation (method + property) & diamond interface inheritance
    c = C()
    d = DiamondImpl()
    actual_3 = {
        "conflict_foo": c.foo(),
        "conflict_label": c.label,
        "diamond_methods": [d.base(), d.left(), d.right()],
    }
    expected_3 = {
        "conflict_foo": "A.foo | B.foo",
        "conflict_label": "A.label | B.label",
        "diamond_methods": ["Right 重写了 Base", "Left", "Right"],
    }
    cases.append({
        "name": "multi_interface_and_diamond_disambiguation",
        "summary": "Verify super<Interface> disambiguation for methods/properties and diamond interface inheritance.",
        "expected": expected_3,
        "actual": actual_3,
        "passed": actual_3 == expected_3,
    })

    # Case 4: fun interface SAM conversion (Kotlin 1.4+)
    def check(text: str, validator: Validator) -> str:
        return f"「{text}」通过校验" if validator.validate(text) else f"「{text}」未通过校验"

    not_empty = Validator(lambda it: len(it) > 0)
    shorter = Validator(lambda it: len(it) <= 10)
    actual_4 = {
        "not_empty_checks": [check("MBSKY", not_empty), check("", not_empty)],
        "shorter_check": check("www.mbsky.com", shorter),
        "default_member_describe": shorter.describe(),
        "fun_interface_since": "1.4",
        "fun_interface_allows_suspend_sam": False,
    }
    expected_4 = {
        "not_empty_checks": ["「MBSKY」通过校验", "「」未通过校验"],
        "shorter_check": "「www.mbsky.com」未通过校验",
        "default_member_describe": "校验器",
        "fun_interface_since": "1.4",
        "fun_interface_allows_suspend_sam": False,
    }
    cases.append({
        "name": "fun_interface_sam_conversion",
        "summary": "Verify Kotlin 1.4+ fun interface SAM conversion, non-abstract member coexistence, and suspend restriction.",
        "expected": expected_4,
        "actual": actual_4,
        "passed": actual_4 == expected_4,
    })

    return cases


def main() -> None:
    payload = {"version": VERSION, "cases": run_cases()}
    sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 离线脚本确认接口默认方法复用、抽象/默认 getter 属性规则、多接口方法与属性消歧及菱形继承、fun interface SAM 转换全部通过。
离线校验接口默认方法、无幕后字段属性、菱形 super<Interface> 消歧与 fun interface

所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。

当前源码 SHA256:246d8e28132d9c35f0c1cdaa0d651dae418064bc4ed2dc2e411ab066af7945a8

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Kotlin 接口实验

所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。

ZIP SHA256:ab6a43da672bdd2866d6234eb0f8c84325b76f9353fb678fca21988f5889e8c1

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

接口中为什么不能写 `val name: String = "Mbsky"`,但可以写 `val displayName: String get() = "[$name]"`?

展开参考解答

因为带初始化器的属性需要幕后字段来保存对象状态,而 Kotlin 接口不持有状态;仅提供 `get()` 的计算属性不生成幕后字段,因此完全合法。

规范与官方依据