Scala 特性:从基础到应用
1. 类型安全与方法定义
在 Scala 中,我们可以定义一个方法 title
来生成 HTML 标题,其代码如下:
def title(text: Text, anchor: Anchor, style: Style): Html =
new Html(
s"<a id='${anchor.value}'>" +
s"<h1 class='${style.value}'>" +
text.value +
"</h1></a>"
)
这个方法接收 Text
、 Anchor
和 Style
类型的参数,并返回一个 Html
对象。如果在调用这个方法时参数顺序错误,编译器能够检测到错误。例如:
scala> title(new Anchor("chap:vcls"), new Style("bold"),
new Text("Value Classes"))
<console>:18: error: type mismatch;
found
: Anchor
required: Text
new Anchor("chap:vcls"),
ˆ
<console>:19: error: type mismatch;
found
: St