So I have an array and I can do:
myArr.lift(0)
...and it gives me option of the value at index 0.
So what actually is happening here? When I try to go to lift definition, IDE takes me to PartialFunction, and I see Array doesn't inherit from it.
And whats the usecase for using lift?
It is true that
Arrayis primitive native to JVM and doesn't have anyliftmethod.However in Scala we have implicit conversions and extension methods and this is what we expect to find when we are able to call methods not defined for some type.
If you write the code in IntelliJ and use a magic shortcut for showing implicits (also available in metals)you'll see that your code is turned into e.g (assuming array of ints):
where
wrapIntArrayis defined inscala.Predef(see Array to ArraySeq section) as(in Scala 2.13
WrappedArrayis deprecated and became aliased toArraySeq).If you are curious why it is in your scope remember that by default Scala compiler imports all definitions from the following paths:
scala- to import allscala.Int,scala.Charand other primitivesscala.Predef- to aliasMaptoscala.collection.immutable.Map, add wrappers aroundArray, let you useprintlninstead of scala.Console.println, etcjava.lang- to import things likeThrowable(I wrote "default" because you can change it with
-Yimportsbut custom predef is something I wouldn't recommend if you don't have experienced devs and good documentation around).What is the use case of
lift? Basically all Scala collections share some common traits andPartialFunctionis one of them:applyto get the value but riskingExceptionif index/key is wrong (e.g.vector(10))applyOrElseto get the value or some fallback valueisDefinedAtso your collection can be used for anything that expectPartialFunctione.g.coll1.collect(coll2)would map all elements ofcoll1into values ofcoll2treating values fromcoll1as keys/indices used for queryingcoll2Reasoning is pretty simple - if you are accessing values in collection like
coll(index)you are using it like function, but since it is not a total mapping it should be a partial function.For
PartialFunctionsliftis just a nice utility to returnOption[Value]instead ofValueorExceptiononapply, that you just got becauseWrappedArraylike any other collection inherit from it.