Dеar स्काला,स्कैला में "केस" अज्ञात फ़ंक्शन वास्तव में कैसे काम करता है?
scala> val f1: ((Int, Int)) => Int = { case (a, b) => a + b }
f1: ((Int, Int)) => Int = <function1>
scala> val f2: (Int, Int) => Int = { case (a, b) => a + b }
f2: (Int, Int) => Int = <function2>
हुह ?!
scala> f1(1, 2)
res2: Int = 3
ठीक है ...
scala> def takesIntInt2Int(fun: (Int, Int) => Int) = fun(100, 200)
takesIntInt2Int: (fun: (Int, Int) => Int)Int
scala> def takesTuple2Int(fun: ((Int, Int)) => Int) = fun(100, 200)
takesTuple2Int: (fun: ((Int, Int)) => Int)Int
scala> takesIntInt2Int(f2)
res4: Int = 300
scala> takesIntInt2Int(f1)
<console>:10: error: type mismatch;
found : ((Int, Int)) => Int
required: (Int, Int) => Int
takesIntInt2Int(f1)
^
scala> takesTuple2Int(f1)
res6: Int = 300
scala> takesTuple2Int(f2)
<console>:10: error: type mismatch;
found : (Int, Int) => Int
required: ((Int, Int)) => Int
takesTuple2Int(f2)
ठीक है। और अब, इसे देखो!
scala> takesTuple2Int { case (a, b, c) => a + b + c }
<console>:9: error: constructor cannot be instantiated to expected type;
found : (T1, T2, T3)
required: (Int, Int)
takesTuple2Int { case (a, b, c) => a + b + c }
^
scala> takesIntInt2Int { case (a, b, c) => a + b + c }
<console>:9: error: constructor cannot be instantiated to expected type;
found : (T1, T2, T3)
required: (Int, Int)
takesIntInt2Int { case (a, b, c) => a + b + c }
की तरह, srsly? o_O दोनों परिणाम required: (Int, Int)
त्रुटि में परिणाम।
फिर ऐसे अज्ञात कार्यों में case
का उपयोग क्यों करें?
'केस' कीवर्ड का उपयोग किये बिना यह सब करने में सक्षम होना बहुत अच्छा होगा। सामान्य डेवलपर के दृष्टिकोण से फ़ंक्शन और आंशिक फ़ंक्शन के लिए वाक्यविन्यास में अंतर क्यों? –
@ माइकलस ईमानदार होने के लिए, यह हमेशा मुझे थोड़ा परेशान करता था। हास्केल और क्लोजर में फ़ंक्शन के पैरामीटर पर सीधे पैटर्न मिलान करने के लिए बहुत सरल वाक्यविन्यास होते हैं। – wingedsubmariner