Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

601
Views
Convert Dp to Px in Kotlin - This cast can never succeed

I ran into a problem while coding in Kotlin. I copy-pasted a java code sample that converts DP to Pixels, in order to place it as a parameter for setting padding programatically. I was expecting the IDE to automatically transform it all to Kotlin, however it failed in the process.

The code in Java looks like the following:

float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (sizeInDp*scale + 0.5f);

After the translation to Kotlin:

val scale = resources.displayMetrics.density
val dpAsPixels = (sizeInDp * scale + 0.5f) as Int 

The cast as Int is marked with the error

"This cast can never succeed"

How can this be fixed?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Why not trying it with an Extension Function such as

val Int.dp: Int get() = (this / getSystem().displayMetrics.density).toInt()

to convert to DP and

val Int.px: Int get() = (this * getSystem().displayMetrics.density).toInt()

to convert to Pixels?

Hope it helps :)

over 4 years ago · Santiago Trujillo Report

0

The error can be solved by removing the cast as Int and instead replace it with the method .toInt()

val scale = resources.displayMetrics.density
val dpAsPixels = (16.0f * scale + 0.5f).toInt()
over 4 years ago · Santiago Trujillo Report

0

If you have value in dimens.xml

<dimen name="textSize">24dp</dimen>

Then, you can get value in pixel as Int

val value = resources.getDimensionPixelSize(R.dimen.textSize)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!