Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Android print to console

I need to print some str to console (Android Studio) using Kotlin. I've tried the:

Log.v()  Log.d()  Log.i()  Log.w()  Log.e()  

methods. But it seems to work only on Java. What should I use to print using Kotlin? Thanks

like image 370
Pavel Bredelev Avatar asked Jul 22 '16 11:07

Pavel Bredelev


People also ask

How do you print something on Kotlin?

d("TAG", "message") {...} You can also use kotlin's print and println function. Kotlin's print and println functions do not print to the Android log. True, they print to the standard output as stated in the docs I setup as source.

How do you print a line on Kotlin?

To print with a new line in Kotlin, use println() statement. println() prints a new line after it prints its argument.

How do I print a variable value in Kotlin?

Kotlin Print Functions To print a variable inside the print statement, we need to use the dollar symbol($) followed by the var/val name inside a double quoted string literal. To print the result of an expression we use ${ //expression goes here } .


2 Answers

There are a couple of ways.

You can use Log.d("TAG", "message"); for example but first you need to import Log.

import android.util.Log  {...}  Log.d("TAG", "message")  {...} 

Source: https://developer.android.com/reference/android/util/Log.html

You can also use kotlin's print and println function.

Example:

{...}  print("message")  println("other message")  {...} 

Source: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/

like image 92
ronniemagatti Avatar answered Sep 17 '22 19:09

ronniemagatti


I've written some extension functions that make use of reified type parameters in order to avoid dealing with declaring log tags in all project's classes. The basic idea is shown by the following snippet:

inline fun <reified T> T.logi(message: String) = Log.i(T::class.java.simpleName, message) 

Basically, you can log something to the logcat with the following invocation (W/O external dependencies):

logi("My log message") 

You can find a gist here. The functions declared in the gist are a little more elaborated given that they allow:

  • Lazy evaluation of the string to be logged out (if for example the string needs to be generated in some way)
  • Logging only when in debug mode by default
  • Use a given class name when you need to log from within an anonymous class that has no name
like image 40
Paolo Avatar answered Sep 21 '22 19:09

Paolo