unable to understand function's signature of scala APIs -


i struggle @ times understand how call function. please me.

i studying lists , writing sample examples of methods.

the andthen defined follows

def andthen[c](k: (a) ⇒ c): partialfunction[int, c] 

i understand have pass function literal andthen. created following code works.

scala> val l = list (1,2,3,4) l: list[int] = list(1, 2, 3, 4)  //x:int works scala> val listandthenexample = l.andthen((x:int) => (x*2)) listandthenexample: partialfunction[int,int] = <function1>  //underscore works scala> val listandthenexample = l.andthen(_*2) listandthenexample: partialfunction[int,int] = <function1> 

as list of integers, has int. c can depending on output of function literal.

the above makes sense.

later tried applyorelse. signature follows

def applyorelse[a1 <: int, b1 >: a](x: a1, default: (a1) ⇒ b1): b1 

from above, understand a1 can int or subclass (upperbound) , b1 return type (depending on in default function).

if understanding of a1 , b1 correct x either int or subclass , default function literal should take int (or subclass) , return b1. tried call function follows doesn't work when use y:int works when use _:int. not understand why

scala> val l = list (1,2,3,4) l: list[int] = list(1, 2, 3, 4)  //this doesnt work cala> val listapplyorelse = l.applyorelse(y:int,(x:int)=>println("wrong arg "+x)) <console>:12: error: not found: value y        val listapplyorelse = l.applyorelse(y:int,(x:int)=>println("wrong arg "+x))                                            ^ //but underscor works scala> val listapplyorelse = l.applyorelse(_:int,(x:int)=>println("wrong arg "+x)) listapplyorelse: int => anyval = <function1> 

question - why did both x:int , _:int worked andthen not applyorelse? question - 'a' , why b1 related a?

according documentation, applyorelse(x, default) equivalent to

if (pf isdefinedat x) pf(x) else default(x) 

in case partial function list i.e. function indices (0 3) values (1,2,3,4). when do

l.applyorelse(y,(x:int)=>println("wrong arg "+x)) 

you're saying "call l(y) if makes sense, otherwise println("wrong arg"+y)". compiler reasonably responds, "what y?"

if use actual value works expected

l.applyorelse(3 ,(x:int)=>println("wrong arg "+x)) // returns 4 l.applyorelse(8 ,(x:int)=>println("wrong arg "+x)) // prints wrong arg 8 

using underscore different, partially applied function (which different partial function!)

val f = l.applyorelse(_:int, (x:int)=>println("wrong arg "+x)) f(8) // prints wrong arg 8 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -