我已经在构造函数中传递了数据,但是如何在另一个类中获取数据?
class EmployeeConst(var name:String , var age:String) {
var profession:String ="Not mentioned"
constructor(name:String, age: String, profession:String):this(name,age){
this.profession = profession
}
fun getDetails() {
Log.i("",""+"Employee details is $name whose profession is $profession and age is $age")
}
}
class FragmentDashboard : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
var person= EmployeeConst("name","sdf","test")
Log.i("Testings",""+person.getDetails()) //here testings is not printing correctly.
return inflater.inflate(R.layout.fragment_dashboard, container, false)
}
在日志中,我没有收到传递的数据
I /测试:kotlin.Unit
答案 0 :(得分:1)
实际上,构造函数传递的值不是问题。您的问题是getDetails不返回任何内容,或者在kotlin中,它是一个单位。
这是我创建的改进:首先,删除重载的构造函数,并使用默认的专业值。该方法与重载方法相同,只是它的行短。接下来,我已修复您的getDetails函数以返回字符串。简而言之,等号是“ return this->”的简写,语法为
fun methodNAme() return this -> something
class EmployeeConst(
var name:String,
var age:String,
var profession:String = "Not mentioned"
) {
fun getDetails() =
"Employee details is $name whose profession is $profession and age is $age"
}
class FragmentDashboard : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
var person= EmployeeConst("name","sdf","test")
Log.i("Testings",""+person.getDetails()) //here testings is not printing correctly.
return inflater.inflate(R.layout.fragment_dashboard, container, false)
}
}
答案 1 :(得分:0)
由于getDetails()
是Unit
函数,因此可以正确记录。
在getDetails()
中正确记录:
fun getDetails(): Unit {
Log.i("Testings", "Employee details is $name whose profession is $profession and age is $age")
}
或返回getDetails()
中的字符串:
fun getDetails(): String {
return "Employee details is $name whose profession is $profession and age is $age"
}
答案 2 :(得分:0)
方法getDetails()
是一个无效函数,即不返回任何内容。当您将此方法称为
Log.i("Testings",""+person.getDetails())
您期望该方法将返回一个字符串。有两种解决方案:
您在Log
类中更改了FragmentDashboard
:
Log.i("Testings")
person.getDetails()
您更改方法getDetails()
的返回值。
fun getDetails(): String {
return "Employee details is $name whose profession is $profession and age is $age"
}
使用第二种方法,您可以在执行操作时调用该方法。