Purpose of "this" in Kotlin classes [closed] - class

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I'm trying to work out the purpose of this in classes. Consider the following example:
class TestMe {
var a: Int = 1
var b: Int = 2
fun setValA(value: Int) {
this.a = value
}
fun setValB(value: Int) {
b = value
}
}
val testInstance1 = TestMe()
val testInstance2 = TestMe()
testInstance1.setValA(3)
testInstance1.setValB(4)
println("instance 2A: ${testInstance2.a}, instance 2B: ${testInstance2.b}") // 1 2
println("instance 1A: ${testInstance1.a}, instance 1B: ${testInstance1.b}") // 3 4
It seems that I can simply omit this value and the results will be the same. Is there anything that I'm missing here?
Many thanks!

Yes, same as Java, but you will have a problem if a is the parameter name also:
fun setValA(a: Int) {
a = a
}
Compilation error:
Val cannot be reassigned
Then you will have to use this:
fun setValA(a: Int) {
this.a = a
}

In addition to user7294900's answer, this can only be omitted in this.<property or method name>, and there are plenty of other uses: e.g. this::class, or
fun doSomething(other: OtherClass) {
other.doSomethingWith(this)
}

Related

Scala Option: isDefined vs map based approach [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 11 months ago.
Improve this question
I have a piece of code implemented in 2 ways:
val c = if(x.y.isDefined){
methodA(....)
} else {
method(....)
}
c
And this:
val c = x.y.
map(methodA(....))
.orElse(Some(mehodB(....))
.getOrElse("")
c
x.y is an Option and methodA, methodB return String values.
Which of these approaches is more preferred in Scala? Personally I find first one to be more easy to understand, but my more scala proficient colleague prefers second one.
use the if or something based on pattern match (by the way, no need for assigning to c if you return the expression)
x.y match {
case Some(_) => methodA()
case None => methodB()
}
x.fold(methodB) { _ => methodA }

How can I write a function which gets a Map[Char, Int] as an input and makes a Set[Case Class]? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Found this stepik task and have no idea what to do:
Write a function which gets a Map[Char, Int] as an input and makes a Set[LetterTree] (LetterTree is the case class below), in which from each (c,w) map entry, we make a LetterLevel(c,w), then we then put it in the said Set[LetterTree].
trait LetterTree {
def weight: Int
}
case class LetterLevel(ch: Char, weight: Int) extends LetterTree
object TreeBuild extends App {
def TreeSetBuild(freqs: Map[Char,Int]): Set[LetterTree] = ???```
}
You could use tupled to construct LetterLevel instances from the tuple elements of the Map:
object TreeBuild extends App {
def treeSetBuild(freqs: Map[Char,Int]): Set[LetterTree] =
freqs.map(LetterLevel.tupled).toSet
}
TreeBuild.treeSetBuild(Map('a'->1, 'b'->2, 'c'->3))
// res1: Set[LetterTree] = Set(LetterLevel(a,1), LetterLevel(b,2), LetterLevel(c,3))

Trying to print method, but it is giving error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to print some attributes of employee along with method. but it is throwing and error.
But I am not able to understand this issue. can someone help to resolve the issue
Error
Error:(12, 43) not found: value grossSalary
println("Employee gross salary is : "+grossSalary)
Code
case class EmployeeGross (empId: Int,empName: String, deptId: Int, var basicSalary: Double) {
var Hra: Double= basicSalary*(30/100)
var Da: Double = basicSalary*(10/100)
var grossSalary: Double = basicSalary + Hra + Da
def grossSalary(basicSalary: Double) = basicSalary + Hra + Da
println("Employee salary information is :"+ empId,empName,deptId,basicSalary)
}
object EmployeeGross {
def main(args: Array[String]): Unit = {
val Eg = new EmployeeGross(1,"test",10,1200.2)
println("Employee gross salary is : "+ grossSalary)
}
}
You are trying to access grossSalary from the EmployeeGross object, probably thinking that this object knows which employee you have in mind. This is not possible to know, you have to use Eg.grossSalary.
Furthermore, you need to multiply by 0.3 and 0.1 rather than 10/100 and 30/100. This is because 10/100 performs integer division, which will yield 0. You could also fix this by writing 10.0/100 which will do floating point division.

List("foo") foreach print other synonyms? [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 4 years ago.
Improve this question
I want to put the print behind
like
"foo" match {
case str => println(str)
}
or
List("foo") foreach print
Are there other best one?
like in Haskell
return "foo" >>= print
so if you just want to have somewhat haskell like semantics you can try the cats or the scalaz libraries. both have IO monads (cats in cats-effects) that would allow you to use the print in a principled manner as in your last example. If you don't care about the purity aspect you could also achieve this with the Id Monad which also both libraries offer.
You can do this:
case class Print(v: String) {
def print = Predef.print(v)
}
object Print {
implicit def stringToString(s: String) = new Print(s)
}
import Print._
object App extends App {
"foo".print
"bar" print
}

SCALA: Type of object [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 6 years ago.
Improve this question
what is the type of this object?
class Zad1[A,B](val fst:A, val snd:B) {
override def toString: String = "(" + fst +","+snd+")"
}
object Zad1 {
def main(args: Array[String]): Unit = {
val v = new Zad1[Int, String](1, "2")
println(v)
}
}
I tried to print the class name with :
println(v.getClass) // would print: class $line8.$read$$iw$$iw$Zad1
The type of a singleton object is its singleton type, ergo, the type of Zad1 is Zad1.type.
This is related to how Scala REPL works.
Though you type just:
scala> class Zad1[A,B](val fst:A, val snd:B) {...}
REPL wraps it into a series of other objects($line8.$read.$iw.$iw), so getClass returns class $line8.$read$$iw$$iw$Zad1.
Read about it here:
Trying to understand how classes declared on the REPL are treated internally
If you run the same as a Scala program(not from REPL), getClass will return something much readable, e.g. class com.example.Zad1