Difference between asInstanceOf[ ] and isInstanceOf[ ] in scala [closed] - scala

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is the difference between asInstanceOf[] and isInstanceOf[]?

Generally speaking, a.asInstanceOf[B] performs the actual cast: it takes an object of type A and returns (if possible) object of type B, whereas a.isInstanceOf[B] returns boolean indicating whether a has type B or not.
Strictly speaking isInstanceOf[B] looks not only if a is of type B, but if a has type B in the upper side inheritance tree (so if B superclass of a, isInstanceOf yield true) and important notice is that isInstanceOf works on the actual object type hierarchy rather on the reference type.

I'd just like to add that the common pattern
if (x.isInstanceOf[B]) {
val b = x.asInstanceOf[B];
...
} else ...
can be written nicely as
x match {
case (b: B) => ...
...
}
This is especially useful if there are multiple tests of this kind for a single x.

Related

why closures are part of scala or any functional programming language [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
By the definition closures are
Scala Closures are functions which use one or more free variables and the return value of this function is dependent of these variable. The free variables are defined outside of the Closure Function and is not included as a parameter of this function.
and the definition of a pure function is
A pure function is a function that depends only on its declared inputs and its internal algorithm to produce its output. It does not read any other values from “the outside world” — the world outside of the function's scope — and it does not modify any values in the outside world.
when functional programming is all about writing code in terms of pure functions,: how come concept like closure is justified in functional programming
please help to clear the understanding
Please consider the following example
def factorial(n: Int): Int = {
lazy val loop: (Int, Int) => Int =
(i, acc) =>
if (i == n + 1) acc
else loop(i + 1, acc * i)
loop(1, 1)
}
This is tail-recursive version of factorial with iterating from 1 to n.
From FP point of view all functions here (either Scala methods or actual scala.Functions) are pure i.e. on the same inputs they return the same output and don't have side effects, their calls can be replaced with their results (referential transparency).
But loop being a closure depends on a parameter from outer scope (namely n).
Reading a variable (free of side-effects) from outer scope (on contrary to writing) is not considered a side effect.
https://alvinalexander.com/scala/fp-book/definition-of-pure-function/
https://en.wikipedia.org/wiki/Pure_function
https://en.wikipedia.org/wiki/Referential_transparency
What is referential transparency?
https://en.wikipedia.org/wiki/Closure_(computer_programming)

scala compare elements in two sequences considering two arguments in element [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
is there any way to get distinct elements by comparing below two sequences only considering 2nd and 3rd arguments of Person element
case class Person(i:Long,name:String,uname2:String,uname:String)
val firstSeq = Seq(Person(null,"aaa","bbb",null),Person(null,"bbb","ccc",null))
val secondSeq = Seq(Person(123456,"aaa","bbb","Bob"),Person(2345678,"ccc","bbb","John"),
Person(34567890,"bbb","ccc","Mike"))
Excepting result from firstSeq perceptive after comparsion Seq(Person(null,"bbb","ccc",null))
Excepting result from secondSeq perceptive after comparsion Seq(Person(2345678,"ccc","bbb","John"))
The question is not that clear, but this code removes elements from two lists where they share the same values of name and uname2, or where there is no corresponding value in the other list.
val (r1, r2) = firstSeq.zip(secondSeq).filterNot {
case (a, b) => a.name == b.name && a.uname2 == b.uname2
}.unzip
Also note that it is much safer to use Option[Int] and Option[String] rather using null to indicate missing values.

Query on scala Collections [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Both tuples and list are accepting the different type values as attached in snippet, then what is the main difference?
Scala is a typed language. You want your program to know as much as possible about the shape of the data it is working with.
List[Any] is not a very useful type. It does not tell you that there are three elements in there, and what their respective types are.
(Int, Double, String) tells you much more.
Lists are for collections of elements of all the same type (but unknown number).
Tuples are for the combination of a fixed number of elements (that can each have their own type).
Tuples can also be seen as ad-hoc versions of case classes (which you have to define first, but then give you named fields, and methods and all that):
val myData = FooDataRecord(id = 1, amount = 1.1, name = "a")

use None or EmptyMyObj in scala? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I understand the concept of None
I also understand how nice it is to have MyObj and also MyEmptyObj but i cant figure out when its better to use None instead of MyEmptyObj and when I should be using MyEmptyObj instead of None. Also I tend not to like to see methods that return Option[MyObj] it clutters my code I prefer to return MyObj and then seamlessly call its methods such as MyObj.toJson and thus MyEmptyObj.toJson will know to represent itself rather than having case None: return some empty json what do you think about this whole subject?
To the other side I can say that None goes very well with flatMap etc, so which to choose?
when to None
and when to Empty?
None is great when you have no default value, but if you have a default, by all means use it.
As a very simple example, if you wanted to define a function called amountOwed, you could do this:
def amountOwed(bill: Int, alreadyPaid: Option[Int]): Option[Int] = {
val owed = bill - alreadyPaid.getOrElse(0)
if(owed == 0) None // nothing to pay!
else Some(owed)
}
But that's much more complex (and annoying) than it needs to be, since 0 makes perfect sense as both a "haven't paid anything" and "don't owe anything":
def amountOwed(bill: Int, alreadyPaid: Int): Int = {
bill - alreadyPaid
}

Is it possible to have type parameters (generics) on classes which are not collections in scala? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
as the questions suggests. Would it ever make sense to even think about generics on non-collections? I have been trying to think this through. A collection is really just a 'wrapper' of other objects, so there has to be a 'wrapper' to direct a generic at?
thanks
Yep. As a minimal example, here is a class that wraps something of type T, where T is generic:
scala> class Wrapper[T](val x: T)
defined class Wrapper
If you give it an Int, then it's a Wrapper[Int]:
scala> new Wrapper(5)
res0: Wrapper[Int] = Wrapper#578ef2b6
If you give it a String, then it's a Wrapper[String]:
scala> new Wrapper("this")
res1: Wrapper[String] = Wrapper#3b16bf07
This is directly analogous to a collection of items of type T:
scala> Vector(1,2,3)
res2: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3)
Yes. It is possible and it makes perfect sense. Pretty much all of the type system of Scala revolves around them. Well, them and the "abstract types".
To learn more you can start from here. Googling for "Scala type parameters" will also give you plenty of useful results.