型別別名通常可以這樣使用:
type Point = (Double, Double)
但我在玩 Scala repl,你也可以這樣做:
type Two = 2
使用此別名,您可以定義函式:
scala> def three(x: Two) = x 1
def three(x: Two): Int
scala> three(1)
-- Error:
1 |three(1)
| ^
| Found: (1 : Int)
| Required: Two
scala> three(2)
val res0: Int = 3
正如您所看到的Two,似乎確實代表了2. 它似乎只適用于值文字,而不適用于變數:
scala> val x = 2
val x: Int = 2
scala> type Two = x
-- Error:
1 |type Two = x
| ^
| Not found: type x
此外,它似乎適用于某些函式值,但不適用于其他函式值:
scala> type AlwaysThree = () => 3
// defined alias type AlwaysThree = () => 3
scala> type AlwaysThree = () => 2 1
-- Error:
1 |type AlwaysThree = () => 2 1
| ^
| Not found: type
我想知道為什么 Scala 允許這樣做。這個小東西在這里有什么原因嗎?
uj5u.com熱心網友回復:
要完成@Silvio 的回答,這些型別的一個很好的用例是聯合型別,用于定義方法可以回傳或接受的一組非常精確的值。
例如:
type LastDay = 28 | 29 | 30 | 31
def getLastDayOfMonth(month: String): LastDay = ???
或者:
type Role = "Driver" | "Passenger"
def getInTheCar(role: Role) = ???
uj5u.com熱心網友回復:
是的,您可以為任何型別定義型別別名,并且2是一種完全有效的型別。具體來說,它是只包含數字2而不包含其他任何內容的型別。
type AlwaysThree = () => 3
函式接受引數并具有回傳型別。這是不帶引數并無條件回傳數字的函式型別3。這種型別的示例函式可能是() => 3.
type AlwaysThree = () => 2 1
這是試圖使用中綴型別別名。它更像是
type AlwaysThree = () => Foo[1, 2]
在哪里而不是型別Foo,我們有 . 你可以很容易地定義一個名為
type [A, B] = A
然后1 2將作為一種型別有效。雖然讓型別 A B來表示的數值A加上的數值B可能有點棘手。我將把它留給讀者作為練習。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358555.html
標籤:斯卡拉
