W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
Elixir中的具名函數(shù)也支持默認(rèn)參數(shù):
defmodule Concat do
def join(a, b, sep \\ " ") do
a <> sep <> b
end
end
IO.puts Concat.join("Hello", "world") #=> Hello world
IO.puts Concat.join("Hello", "world", "_") #=> Hello_world
任何表達(dá)式都可以作為默認(rèn)值,但它在函數(shù)定義時(shí)不會(huì)執(zhí)行;僅僅是存貯備用。每當(dāng)必須使用默認(rèn)值的時(shí)候,表達(dá)式才會(huì)被執(zhí)行:
defmodule DefaultTest do
def dowork(x \\ IO.puts "hello") do
x
end
end
iex> DefaultTest.dowork
hello
:ok
iex> DefaultTest.dowork 123
123
iex> DefaultTest.dowork
hello
:ok
當(dāng)帶默認(rèn)值的函數(shù)有多個(gè)從句時(shí),就需要?jiǎng)?chuàng)建一個(gè)不包含函數(shù)內(nèi)容的函數(shù)頭來(lái)聲明默認(rèn)值:
defmodule Concat do
def join(a, b \\ nil, sep \\ " ")
def join(a, b, _sep) when is_nil(b) do
a
end
def join(a, b, sep) do
a <> sep <> b
end
end
IO.puts Concat.join("Hello", "world") #=> Hello world
IO.puts Concat.join("Hello", "world", "_") #=> Hello_world
IO.puts Concat.join("Hello") #=> Hello
當(dāng)使用默認(rèn)值時(shí),我們要當(dāng)心函數(shù)定義的重疊:
defmodule Concat do
def join(a, b) do
IO.puts "***First join"
a <> b
end
def join(a, b, sep \\ " ") do
IO.puts "***Second join"
a <> sep <> b
end
end
如果我們將上述代碼保存到文件“concat.ex”中并編譯,Elixir將提出警告:
concat.ex:7: warning: this clause cannot match because a previous clause at line 2 always matches
編譯器告訴我們當(dāng)用兩個(gè)參數(shù)調(diào)用join函數(shù)時(shí),總會(huì)使用第一個(gè)join函數(shù)定義,而第二個(gè)定義只有當(dāng)傳遞三個(gè)參數(shù)時(shí)才會(huì)被調(diào)用:
$ iex concat.exs
iex> Concat.join "Hello", "world"
***First join
"Helloworld"
iex> Concat.join "Hello", "world", "_"
***Second join
"Hello_world"
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: