asInstanceOf err in Scala - scala

why it is give me an error
I already write the code correctly
code :
x = 1 //true
val x1 = x.asInstanceOf[Boolean]
if (x1) {
println(s"Hello, $x1")
}

The problem is that the comment on this line is not correct:
x = 1 // true
1 is not true because 1 is of type Int and true is of type Boolean. Scala is strongly typed so it doesn't automatically convert between these two types, unlike languages such as C and Python.
To fix it, just convert the Int to a Boolean like this:
val x1 = x != 0

Related

trying to solve palindrome integer in python 3 code is working but giving wrong output

enter code here''' class Solution:
def isPalindrome(self, x: int) -> bool:
x = str(x)
lst = list(x)
str_val = []
count = len(lst)
for i in range(len(lst)):
str_val.append(lst[count-1])
count -= 1
value = [str(i) for i in str_val]
res = int("".join(value))
if int(res) == x:
return True
else:
return False
'''
trying to solve palindrome integer in python 3 code is working but giving wrong output.
If you're just trying to check for integers only, you can try the below code. It's a two pointer approach.
class Solution:
def isPalindrome(self, x: int) -> bool:
x = str(x)
if len(x) < 2: return True
s, e = 0, len(x)-1
while s < e:
if x[s] != x[e]: return False
s += 1
e -= 1
return True
You can also do this in one line in python to check if a number (as a string) and it's reverse is same or not.
str(x) == str(x)[::-1]
The reason your results are not as expected is due to the type change that you make in the first line of your function.
x = str(x)
It is necessary to convert x into a string so that you can iterate over it and put it into a list for your second line of code:
lst = list(x)
but by re-assigning that back to x, you get an x at the end of the function call that is not equal to the int(res) when you make the final comparison to get your boolean:
if int(res) == x:
A simple solution is to just not assign the temporary string that is created from the parameter x back to itself, and rather to just merge the first and second lines of your function into one:
lst = list(str(x))

When is semicolon mandatory in scala?

I am learning how to program in Scala and was being told that semicolon is optional in Scala. So with that in mind, I tried with the following nested block of code which does not have semi colon. However, it throws an error in the Scala REPL
scala> { val a = 1
| {val b = a * 2
| {val c = b + 4
| c}
| }
| }
<console>:17: error: Int(1) does not take parameters
{val b = a * 2
And the sample with semi colon worked perfectly fine.
scala> { val a = 1;
| { val b = a*2;
| { val c = b+4; c}
| }
| }
res22: Int = 6
Therefore it seems to me that semi colon is not really optional and is mandatory in some situations. May I ask in what situation the semi colon is mandatory?
I'll try to extract the essence from your example.
Consider the following code snippet:
{ val x = 1 { val y = 2 } }
To the compiler, it looks like syntactic sugar for
{ val x = 1.apply({ val y = 2 }) }
But the object 1 does not have an apply method that takes blocks, therefore the compiler produces an error:
error: Int(1) does not take parameters
{ val x = 1 { val y = 2 } }
^
Contrast this to
object I { def apply(a: => Any): Unit = () }
{ val x = I { val y = 2 } }
This works, because I now does have an apply method.
To make the differentiation between these two cases a little bit easier, the compiler requires a semicolon in the first case.
Now one might wonder why a line break between val x = 1 and the { is not converted into an inferred semicolon. I think the relevant quote from the spec would be this (1.2 Newline Characters) (most parts of enumerations omitted ([...]), emphasis mine):
The Scala grammar [...] contains productions where
optional nl tokens, but not semicolons, are accepted. This has the
effect that a newline in one of these positions does not terminate an
expression or statement. These positions can be summarized as follows:
[...]
in front of an opening brace ‘{’, if that brace is a legal continuation of the current statement or expression,
[...]
Note that this quote covers only the case with a single optional line break. It does not hold for two or more consecutive line breaks, e.g.
scala> {
| val x = 1
|
| { val y = 2 }
| }
is valid, and { val y = 2 } is parsed as a separate expression.
I guess the motivation was to allow embedded DSL's with syntactic sugar like this:
MY_WHILE(x >= 0)
{
println(x)
x -= 1
}
It would be really strange if one had to enclose each such MY_WHILE-statement into an additional pair of round parentheses, wouldn't it?
Adding to Andrey's answer, it's rare that you write code like this in idiomatic Scala, but, when you do, you should use locally:
{
val a = 1
locally {
val b = a * 2
locally {
val c = b + 4
c
}
}
}
This case is exactly why locally exists.

Kotlin: Curly braces around several expressions (or statements)

I think this question is somewhat related to Kotlin function declaration: equals sign before curly braces
In Scala, every statement is an expression (possibly with Unit type). If we surround multiple expressions with braces, then the final expression is the actual value of the curly braced part. Therefore,
// Scala
val a = {
val b = 1
val c = b + b
c + c
}
println(a)
The type of a is Int and the code prints the value 4.
However, in Kotlin, this is somewhat different.
If we do the same thing in the Kotlin,
// Kotlin
val a = {
val b = 1
val c = b + b
c + c
}
println(a)
The type of a is () -> Int and the code prints the Function0<java.lang.Integer>, which means a 0-ary function object with result type Int.
So if we want to print the value 4, we need to do println(a()).
In fact, the expression {} in Kotlin is a function () -> ().
I cannot find an explanation about this in Kotlin official reference pages. Without a parameter list or ->, curly braces make a function?
When I use Scala, I write many codes like the first code. However, in Kotlin, it creates a function object and we have to call the function, which may be an overhead in a loop or recursion.
Is there any document about this thing: just curly braces make a function object?
Any way to workaround the overhead in the second code if it is used many times?
EDIT
Here is the actual code that iterates many times:
in Java
while ((count = input.read(data, 0, BYTE_BLOCK_SIZE)) != -1) {
....
}
in Scala
while {
count = input.read(data, 0, BYTE_BLOCK_SIZE)
count != -1
} {
....
}
in Kotlin
while ({
count = input.read(data, 0, BYTE_BLOCK_SIZE)
count != -1
}()) {
...
}
You can see, only Kotlin makes a lot of function objects and calls them.
In Kotlin {} are always a lambda expression or a part of a syntax construct like while(true) {}. Probably different from Scala, but easy to grasp, nonetheless.
What you probably want is:
val a = run {
val b = 1
val c = b + b
c + c
}
println(a)
Kotlin has no build-in concept of "code blocks anywhere". Instead we use standard functions-helpers like run in the example above.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/run.html
If {} defines a function, you can just call the function upon declaring it, which will immediately evaluate it:
val a = {
val b = 1
val c = b + b
c + c
}()
println(a)
prints 4. (Note the () at the end of the block)
In Scala, every statement is an expression (possibly with Unit type)
That's not exactly true. Check: Is everything a function or expression or object in scala?
As Zoltan said {} defines functions so instead of:
// Kotlin
val a = {
val b = 1
val c = b + b
c + c
}
println(a)
it should be:
// Kotlin
val a = {
val b = 1
val c = b + b
c + c
}
println(a()) //you defined a function, which returns `4`, not expression
or
// Kotlin
val a = {
val b = 1
val c = b + b
c + c
}() //note these braces
println(a)
If you would like to print a value, not function, you can try to declare the variable and then use one of Kotlin functions to change a value like in example below:
var sum = 0
ints.filter { it > 0 }.forEach {
sum += it
}
print(sum)
Read: Higher-Order Functions and
Lambdas
Hope it will help

Scala - Type Mismatch Found Unit : required Array[Int]

Why does the method give a compile error in NetBeans
( error in question -- Type Mismatch Found Unit : required Array[Int] )
def createArray(n:Int):Array[Int] =
{
var x = new Array[Int](n)
for(i <- 0 to x.length-1)
x(i) = scala.util.Random.nextInt(n)
}
I know that if there was a if clause - and no else clause - then why we get the type mismatch.
However, I am unable to resolve this above error - unless I add this line
return x
The error is not happening because the compiler thinks what happens if n <= 0
I tried writing the function with n = 10 as hardcoded
Thoughts ?
Your for comprehension will be converted into something like:
0.to(x.length - 1).foreach(i => x(i) = scala.util.Random.nextInt(i))
Since foreach returns (), the result of your for comprehension is (), so the result of the entire function is () since it is the last expression.
You need to return the array x instead:
for(i <- 0 to x.length-1)
x(i) = scala.util.Random.nextInt(n)
x
Yet another one,
def createArray(n: Int): Array[Int] = Array.fill(n) { scala.util.Random.nextInt(n) }
Then, for instance
val x: Array[Int] = createArray(10)
You could do something cleaner in my own opinion using yield :
def createArray(n:Int):Array[Int] =
(for(i: Int <- 0 to n-1) yield scala.util.Random.nextInt(n)).toArray
This will make a "one lined function"

Why can't i define a variable recursively in a code block?

Why can't i define a variable recursively in a code block?
scala> {
| val test: Stream[Int] = 1 #:: test
| }
<console>:9: error: forward reference extends over definition of value test
val test: Stream[Int] = 1 #:: test
^
scala> val test: Stream[Int] = 1 #:: test
test: Stream[Int] = Stream(1, ?)
lazy keyword solves this problem, but i can't understand why it works without a code block but throws a compilation error in a code block.
Note that in the REPL
scala> val something = "a value"
is evaluated more or less as follows:
object REPL$1 {
val something = "a value"
}
import REPL$1._
So, any val(or def, etc) is a member of an internal REPL helper object.
Now the point is that classes (and objects) allow forward references on their members:
object ForwardTest {
def x = y // val x would also compile but with a more confusing result
val y = 2
}
ForwardTest.x == 2
This is not true for vals inside a block. In a block everything must be defined in linear order. Thus vals are no members anymore but plain variables (or values, resp.). The following does not compile either:
def plainMethod = { // could as well be a simple block
def x = y
val y = 2
x
}
<console>: error: forward reference extends over definition of value y
def x = y
^
It is not recursion which makes the difference. The difference is that classes and objects allow forward references, whereas blocks do not.
I'll add that when you write:
object O {
val x = y
val y = 0
}
You are actually writing this:
object O {
val x = this.y
val y = 0
}
That little this is what is missing when you declare this stuff inside a definition.
The reason for this behavior depends on different val initialization times. If you type val x = 5 directly to the REPL, x becomes a member of an object, which values can be initialized with a default value (null, 0, 0.0, false). In contrast, values in a block can not initialized by default values.
This tends to different behavior:
scala> class X { val x = y+1; val y = 10 }
defined class X
scala> (new X).x
res17: Int = 1
scala> { val x = y+1; val y = 10; x } // compiles only with 2.9.0
res20: Int = 11
In Scala 2.10 the last example does not compile anymore. In 2.9.0 the values are reordered by the compiler to get it to compile. There is a bug report which describes the different initialization times.
I'd like to add that a Scala Worksheet in the Eclipse-based Scala-IDE (v4.0.0) does not behave like the REPL as one might expect (e.g. https://github.com/scala-ide/scala-worksheet/wiki/Getting-Started says "Worksheets are like a REPL session on steroids") in this respect, but rather like the definition of one long method: That is, forward referencing val definitions (including recursive val definitions) in a worksheet must be made members of some object or class.