Working with fragments in my Java Code I checked if the user is logged into his Firebase Account or not, if he was logged in he got displayed the right View otherwise a "You are not logged in" Fragment got inflated.
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
/**
* USER IS SIGNED IN
*/
View view = inflater.inflate(R.layout.fragment_calendar, container, false);
return view;
} else {
/**
* NO USER IS SIGNED IN
*/
View view = inflater.inflate(R.layout.fragment_unregistred, container, false);
return view;
}
}
Now doing this in Kotlin somehow seems not to be as easy as it should, it says that "return" is not allowed at the same position as I got it in Java:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
if(getUID.requestUserExistence() != null) {
FirebaseAuth.getInstance().currentUser!!.getIdToken(true).addOnCompleteListener{task ->
if(task.isSuccessful) {
val view = inflater.inflate(R.layout.fragment_crackthecode, container, false)
return view
}
}
}
}
So why is this happening?
Operator if in Kotlin is an expression. Considering your case we can rewrite it as the following:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val user = FirebaseAuth.getInstance().getCurrentUser()
return if (user != null) {
inflater.inflate(R.layout.fragment_calendar, container, false)
} else {
inflater.inflate(R.layout.fragment_unregistred, container, false)
}
}
Considering your second example in Kotlin it looks different from Java: there is a OnCompleteListener
which you can't use to return a View
for onCreateView
method. If you want return a variable from onCreateView
method you shouldn't return it from a callback's (listener's) method. If you rewrite the same code in Java, adding OnCompleteListener
, you will get the same or similar error and your code will not be compiled.