error: expecting property name or receiver type - Kotlin - kotlin

Not able to figure out what is wrong with below code and why I am getting below error :
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun pathSum(root: TreeNode?, sum: Int): List<List<Int>> {
var result : List<MutableList<Int>> = listOf(mutableListOf())
var path : MutableList<Int> = mutableListOf()
dfs(root, sum, result, path)
return result
}
fun dfs(root: TreeNode?, sum: Int, result: List<MutableList<Int>>, path: MutableList<Int>){
if(root == null) return
path.add(sum)
dfs(root.left, sum - root.val, result, path)
dfs(root.right, sum - root.val, result, path)
if(sum == 0 &&
root.left == null &&
root.right == null) {
result.add(path)
}
path.remove(path.size() - 1)
}
}
I am getting below lots of compile time errors while running above code, new to Kotlin struggling to figure out root cause :
Line 24: Char 38: error: expecting property name or receiver type
dfs(root.left, sum - root.val, result, path)
^
Line 24: Char 46: error: expecting an element
dfs(root.left, sum - root.val, result, path)

val is a keyword in kotlin. If you want to use it as a name of a field,
you need to wrap it into backticks: `val`
(actually, the code example in the comment before your code shows that).

Related

kotlin product of odd or even integers

The problem I'm working on accepts a number string and will output the product of the odd or even numbers in the string. While the product of purely number string is working fine, my code should also accept strings that is alphanumeric (ex: 67shdg8092) and output the product. I'm quite confused on how I should code the alphanumeric strings, because the code I have done uses toInt().
Here's my code:
fun myProd(Odd: Boolean, vararg data: Char): Int {
var bool = isOdd
var EvenProd = 1
var OddProd = 1
for (a in data)
{
val intVal = a.toString().toInt()
if (intVal == 0)
{
continue
}
if (intVal % 2 == 0)
{
EvenProd *= intVal
}
else
{
OddProd *= intVal
}
}
if(bool == true) return OddProd
else return EvenProd
}
Use toIntOrNull instead of toInt. It only converts numeric string
val intVal = a.toString().toIntOrNull()
if (intVal == null || intVal == 0) {
continue
}
Starting from Kotlin 1.6 you can also use a.digitToIntOrNull().
P.S. Your method could be also rewritten in functional style
fun myProd(isOdd: Boolean, input: String): Int {
return input.asSequence()
.mapNotNull { it.toString().toIntOrNull() } // parse to numeric, ignore non-numeric
.filter { it > 0 } // avoid multiplying by zero
.filter { if (isOdd) it % 2 != 0 else it % 2 == 0 } // pick either odd or even numbers
.fold(1) { prod, i -> prod * i } // accumulate with initial 1
}

Continuous Subarray Sum in Kotlin

I am trying to learn Kotlin these days and thought of converting my Java leetcode solutions into kotlin to understand the syntax and practice its nuances. I am still facing issues with Collections. Below is the code for one of the famous interview problem Continuous Subarray Sum.
Details about use cases: https://leetcode.com/problems/continuous-subarray-sum/
class Solution {
fun checkSubarraySum(nums: IntArray, k: Int): Boolean {
var map = mutableMapOf<Int,Int>()
var sum = 0
map.put(0,-1)
for (i in 0 until nums.size-1){
sum += nums[i]
if (k != 0){
sum = sum % k
}
if (map.containsKey(sum)){
if (i - map.get(sum) > 1){
return true
}
}
else{
map.put(sum,i)
}
}
return false
}
}
I am getting this error.
Line 15: Char 25: error: type mismatch: inferred type is Int? but Int was expected
if (i - map.get(sum) > 1){
What am I doing wrong here?
Please note that I am really new to this language so this question might be dumb. ^
Got it. Thank you #HenryTwist
Int is a nullable entity denoted by Int? and I am trying to access Int here: So that's the reason compiler needs '!!' (non-null asserted)
class Solution {
fun checkSubarraySum(nums: IntArray, k: Int): Boolean {
var map = mutableMapOf<Int,Int>()
var sum = 0
map.put(0,-1)
for (i in 0 until nums.size){
sum += nums[i]
if (k != 0){
sum = sum % k
}
if (map.containsKey(sum)){
if (i - map.get(sum)!! > 1){
return true
}
}
else{
map.put(sum,i)
}
}
return false
}
}

I'm getting a compile time error that I don't know how to solve: error: expecting property name or receiver type - Kotlin

/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
var head : ListNode?
var tail: ListNode?
var firstPointer : ListNode? = l1
var secondPointer : ListNode? = l2
while( firstPointer != null || secondPointer != null){
var next : ListNode?
if (firstPointer == null || secondPointer == null){
if (secondPointer != null){
next.val = secondPointer.val
secondPointer = secondPointer.next
}else {
next.val = firstPointer.val
firstPointer = firstPointer.next
}
}else if(firstPointer.val <= secondPointer.val) {
next.val = firstPointer.val
firstPointer = firstPointer.next
}else if(secondPointer.val <= firstPointer.val ){
next.val = secondPointer.val
secondPointer = secondPointer.next
}
if (head == null){
head = next
tail = next
}else {
tail.next = next
tail = next
}
}
return head
}
}
getting a lot of compile time errors
Line 22: Char 29: error: expecting property name or receiver type
next.val = secondPointer.val
^
Line 25: Char 29: error: expecting property name or receiver type
next.val = firstPointer.val
^
Line 28: Char 39: error: type expected
}else if(firstPointer.val <= secondPointer.val) {
^
val is a keyword in kotlin. If you want to use it as a name of a field, you need to wrap it into backticks: secondPointer.`val`, firstPointer.`val` (actualy, code example in the comment before your code shows that).
Well, I don't know Kotlin well, but from my perspective this might be the problem:
var next : ListNode?
Because you define a variable, but it is still null.
When you then try to access its field val you can't, because null has no such field.

Kotlin decomposing numbers into powers of 2

Hi I am writing an app in kotlin and need to decompose a number into powers of 2.
I have already done this in c#, PHP and swift but kotlin works differently somehow.
having researched this I believe it is something to do with the numbers in my code going negative somewhere and that the solution lies in declaring one or more of the variable as "Long" to prevent this from happening but i have not been able to figure out how to do this.
here is my code:
var salads = StringBuilder()
var value = 127
var j=0
while (j < 256) {
var mask = 1 shl j
if(value != 0 && mask != 0) {
salads.append(mask)
salads.append(",")
}
j += 1
}
// salads = (salads.dropLast()) // removes the final ","
println("Salads = $salads")
This shoud output the following:
1,2,4,8,16,32,64
What I actually get is:
1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,
Any ideas?
This works for the one input that you specified, at the very least:
fun powersOfTwo(value :Long): String {
val result = ArrayList<String>()
var i = 0
var lastMask = 0
while (lastMask < value) {
val mask = 1 shl i
if (value != 0.toLong() && mask < value) {
result.add(mask.toString())
}
lastMask = mask
i += 1
}
return result.joinToString(",")
}
Ran it in a unit test:
#Test
fun addition_isCorrect() {
val result = powersOfTwo(127)
assertEquals("1,2,4,8,16,32,64", result)
}
Test passed.
You can get a list of all powers of two that fit in Int and test each of them for whether the value contains it with the infix function and:
val value = 126
val powersOfTwo = (0 until Int.SIZE_BITS).map { n -> 1 shl n }
println(powersOfTwo.filter { p -> value and p != 0}.joinToString(","))
// prints: 2,4,8,16,32,64
See the entire code in Kotlin playground: https://pl.kotl.in/f4CZtmCyI
Hi I finally managed to get this working properly:
fun decomposeByTwo(value :Int): String {
val result = ArrayList<String>()
var value = value
var j = 0
while (j < 256) {
var mask = 1 shl j
if ((value and mask) != 0) {
value -= mask
result.add(mask.toString())
}
j += 1
}
return result.toString()
}
I hope this helps someone trying to get a handle on bitwise options!
Somehow you want to do the "bitwise AND" of "value" and "mask" to determine if the j-th bit of "value" is set. I think you just forgot that test in your kotlin implementation.

Kotlin multiplication between nullable and non-nullable float errors even with null check

I'm porting a class called ShapeData from Java which is filled with nullable types. It looks like this:
class ShapeData {
var type: Shape.Type? = null // Circle, Edge, Polygon, Chain
// PolygonShape / ChainShape
var vertices: FloatArray? = null
var offset: Int? = null
var len: Int? = null
// setAsBox
var hx: Float? = null
var hy: Float? = null
var center: Vector2? = null
var angle: Int? = null
// CircleShape
var radius: Float? = null
var position: Vector2? = null
// EdgeShape
var v1: Vector2? = null
var v2: Vector2? = null
}
These properties are nullable because they are read from JSON and might not exist, and since certain fields allow negative values -1 is not a valid default.
Certain properties need to be scaled if they exist so for that I'm converting a previously static method to a Kotlin top-level function, however I've run into a bit of an issue:
fun scaledShapeData(data: ShapeData, scalar: Float): ShapeData {
return ShapeData().apply {
type = data.type
vertices = data.vertices?.map { it * scalar }?.toFloatArray()
offset = data.offset
len = data.len
hx = if(data.hx != null) data.hx * scalar else null // This is marked as an error with "None of the following functions can be called with the arguments supplied" message
}
}
The precise message i get is this (image since Android Studio doesn't let me select and copy the message):
I've also tried to replicate this in the Kotlin playground with this piece of code:
fun main(args: Array<String>) {
var test1 : Float? = 2f
val test2 : Float = 2f
var test3 : Float? = if(test1 != null) test1 * test2 else null
print(test3)
}
And this compiles and outputs 4.0 as expected. As far as I can see the two code samples are near identical.
What exactly am I doing wrong and how can I fix this?
// This is marked as an error with "None of the following functions can be called with the arguments supplied" message
hx = if(data.hx != null) data.hx * scalar else null
The difference between your playground example and this example is that data.hx may change between the null check and the multiplication.
You can use the following instead, using the times function on Int:
hx = hdata.hx?.times(scalar)
since * is translated to times.