Issue
I don´t know why it doesn´t work.. I cant use if or when functions in class or in the "playerPosition" function..
class Player(val name:String, val nachname: String, val nr:Int) {
var position = mutableListOf<Int>(0,1,2,3)
var playerPosi = Int
fun playerPosition(){
if(playerPosi < 3 ){
}
}
}
And the next question is, how can I use a function from a class in the main func.? Maybe like this
class Player(val name:String, val nachname: String, val nr:Int, var playerPosi : Int) {
var position = mutableListOf<Int>(0,1,2,3)
fun playerPosition(){
if(playerPosi > 3 ){
println("Diese Position gibt es nicht")
}
}
}
MAIN FUNCTION
fun main(){
val team2 = mutableListOf<Player>()
team2.add(Player("Berkan", "Kutlu", 10,4))
val spieler = Player("Wesley","Sneijder",10,4)
playerPosition()
println("${team2.first().playerPosi}")
}
notice Im trying to set the max Int from playerPosi to 3. Because of Offense, Middfield and Defense and Keeper If Ive the numbers from 0 to 3 I will try to identify 0 as Keeper 1 as Defense and so on.
Thanks for you patience with me :D
Solution
First question
The problem here is not the if keyword, it's because the property playerPosi is wrong.
Instead of writing :
var playerPosi = Int
you need to write :
var playerPosi: Int
Why ?
In kotlin, you have two way to declare a variable / property :
- var : mutable variable / property, you can change it's value
- val : read-only variable (check Tenfour04 response)
After the var / val keyword you give it a name
And after that you have three choices :
- Directly give a value and kotlin will infer the type
var playerPosi = 1
- Give it a type and initialize it latter
var playerPosi: Int
- Give it a type and initialize it
var playerPosi: Int = 1
Second Question
If you want to call a method of an object (here it's Player), you need to :
- Instantiate it
- Get the reference
- Call the method from the reference
So, if we take your sample :
val team2 = mutableListOf<Player>()
team2.add(Player("Berkan", "Kutlu", 10,4))
val spieler = Player("Wesley","Sneijder",10,4) // Instantiate + take the reference on spieler variable.
speiler.playerPosition() // here you call the playerPosition method with the speiler variable
println("${team2.first().playerPosi}")
Answered By - Dinamots
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.